在C ++ 20之前将malloc用于int未定义行为 [英] Is using malloc for int undefined behavior until C++20

查看:110
本文介绍了在C ++ 20之前将malloc用于int未定义行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was told that the following code has undefined behavior until C++20:

int *p = (int*)malloc(sizeof(int));
*p = 10;

是真的吗?

论点是<$的生存期在为对象分配值之前,未启动c $ c> int 对象( P0593R6 )。要解决此问题,应使用 new 放置:

The argument was that the lifetime of the int object is not started before assigning the value to it (P0593R6). To fix the problem, placement new should be used:

int *p = (int*)malloc(sizeof(int));
new (p) int;
*p = 10;

我们真的必须调用一个琐碎的默认构造函数来启动对象的生存期吗?

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

同时,该代码在纯C语言中没有未定义的行为。但是,如果我在C代码中分配 int 并将其用于C ++代码?

At the same time, the code does not have undefined behavior in pure C. But, what if I allocate an int in C code and use it in C++ code?

// 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 still undefined behavior?

推荐答案


是真的吗?

Is it true?

是。从技术上讲,没有任何内容。

Yes. Technically speaking, no part of:

int *p = (int*)malloc(sizeof(int));

实际上创建类型为 int 的对象,因此取消引用 p 是UB,因为那里没有实际的 int

actually creates an object of type int, so dereferencing p is UB since there is no actual int there.


我们真的必须调用默认的构造函数来启动对象的生命周期吗?

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

必须来避免C ++ 20之前的未定义行为?是。如果不这样做,编译器实际上会造成伤害吗?

Do you have to per the C++ object model to avoid undefined behavior pre-C++20? Yes. Will any compiler actually cause harm by you not doing this? Not that I'm aware of.


[...]仍然是未定义的行为吗?

[...] Is it still undefined behavior?

是。在C ++ 20之前的版本中,您实际上仍未在任何地方创建 int 对象,因此它是UB。

Yes. Pre-C++20, you still didn't actually create an int object anywhere so this is UB.

这篇关于在C ++ 20之前将malloc用于int未定义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆