gpt4 book ai didi

c++ - 我们真的需要放置新表达式吗?

转载 作者:行者123 更新时间:2023-12-02 16:06:57 25 4
gpt4 key购买 nike

我正在努力理解 placement new-expressions在 C++ 中。

This Stack Overflow answer声明 T* p = new T(arg); 等同于

void* place = operator new(sizeof(T));  // storage allocation
T* p = new(place) T(arg); // object construction

并且 delete p; 等同于

p->~T();             // object destruction
operator delete(p); // storage deallocation

为什么我们需要 T* p = new(place) T(arg); 中的 placement new-expression 来构造对象,下面不是等价的吗?

T* p = (T*) place;
*p = T(arg);

最佳答案

首先要注意的是 *p = T(arg); 是赋值,不是构造。

现在让我们阅读标准([basic.life]/1):

... The lifetime of an object of type T begins when:

  • storage with the proper alignment and size for type T is obtained, and
  • its initialization (if any) is complete (including vacuous initialization)

对于一般类型 T,如果使用放置 new 就可以完成初始化,但事实并非如此。做

void* place = operator new(sizeof(T));
T* p = (T*)place;

不会开始 *p 的生命周期。

同一部分内容为 ( [basic.life]/6 ):

... Before the lifetime of an object has started but after the storage which the object will occupy has been allocated ... any pointer that represents the address of the storage location where the object will be ... located may be used but only in limited ways. ... The program has undefined behavior if:...

  • the pointer is used to access a non-static data member or call a non-static member function of the object,...

operator= 是一个非静态成员函数并执行 *p = T(arg);,这等同于 p->operator=( T(arg)),导致未定义的行为。

一个简单的例子是一个包含指针作为数据成员的类,它在构造函数中初始化并在赋值运算符中取消引用。如果没有放置new,构造函数将不会被调用,指针也不会被初始化(complete example)。

关于c++ - 我们真的需要放置新表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69158516/

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