这是什么语法- new (this) T();

what is this syntax - new (this) T();

本文关键字:this new 是什么 语法      更新时间:2023-10-16

我遇到了这样的c++代码:

T& T::operator=(const T&t) 
{
   ...
   new (this) T(t);
   ...
}

这一行对我来说太陌生了:new (this) T(t);

我可以看到它正在调用复制构造函数来填充"this",但不知何故,我只是无法理解语法。我想我已经习惯了this = new T(t);

你能帮我吗?

这就是所谓的new placement操作符。它在圆括号中的表达式指定的地址处构造一个对象。例如,复制赋值操作符可以如下方式定义

const C& C::operator=( const C& other) {
   if ( this != &other ) {
      this->~C(); // lifetime of *this ends
      new (this) C(other); // new object of type C created
   }
   return *this;
}

在本例中,首先使用显式调用析构函数取消当前对象,然后在此地址使用复制构造函数创建新对象。

即这个new操作符不分配新的内存区。它使用已经分配的内存。

这个例子取自c++标准。至于我,我不会返回const对象。将操作符声明为

会更正确。
C& C::operator=( const C& other);