gpt4 book ai didi

c++ - 在 C++20 之前将 malloc 用于 int 未定义行为

转载 作者:行者123 更新时间:2023-12-01 08:23:04 24 4
gpt4 key购买 nike

有人告诉我,以下代码在 C++20 之前具有未定义的行为:

int *p = (int*)malloc(sizeof(int));
*p = 10;
这是真的吗?
论点是 int 的生命周期对象在为其分配值之前未启动( P0593R6 )。要解决此问题,请放置 new应该使用:
int *p = (int*)malloc(sizeof(int));
new (p) int;
*p = 10;
我们真的必须调用一个微不足道的默认构造函数来启动对象的生命周期吗?
同时,代码在纯 C 中没有未定义的行为。但是,如果我分配一个 int 会怎样?在 C 代码中并在 C++ 代码中使用它?
// C source code:
int *alloc_int(void)
{
int *p = (int*)malloc(sizeof(int));
*p = 10;
return p;
}

// C++ source code:
extern "C" int *alloc_int(void);

auto p = alloc_int();
*p = 20;
它仍然是未定义的行为吗?

最佳答案

Is it true?


是的。从技术上讲,不属于:
int *p = (int*)malloc(sizeof(int));
实际上创建了一个 int 类型的对象,因此取消引用 p是 UB,因为没有实际 int那里。

Do we really have to call default constructor that is trivial to start the life time of the object?


您是否必须按照 C++ 对象模型来避免 C++20 之前的未定义行为?是的。如果您不这样做,任何编译器实际上会造成伤害吗?不是我所知道的。

[...] Is it still undefined behavior?


是的。在 C++20 之前,您实际上还没有创建 int对象任何地方,所以这是 UB。

关于c++ - 在 C++20 之前将 malloc 用于 int 未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63379066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com