問題:
I was told that the following code has undefined behavior until C++20:有人告訴我,以下代碼在 C++20 之前具有未定義的行爲:
int *p = (int*)malloc(sizeof(int));
*p = 10;
Is that true?真的嗎?
The argument was that the lifetime of the int
object is not started before assigning the value to it ( P0593R6 ).論點是int
對象的生命週期在爲它分配值之前沒有開始( P0593R6 )。 To fix the problem, placement new
should be used:爲了解決這個問題,應該使用placement new
:
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?我們真的必須調用一個微不足道的默認構造函數來啓動對象的生命週期嗎?
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 中沒有未定義的行爲。但是,如果我在 C 代碼中分配一個int
並在 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 still undefined behavior?它仍然是未定義的行爲嗎?