我遇到了这样的C++代码:
T& T::operator=(const T&t)
{
...
new (this) T(t);
...
}
Run Code Online (Sandbox Code Playgroud)
这条线对我来说太陌生了:new (this) T(t);
我可以看到它正在调用复制构造函数来填充"this",但不知怎的,我只是无法理解语法.猜猜我已经习惯了this = new T(t);
你能救我吗?
它就是所谓的新贴牌运营商.它在括号中的表达式指定的地址处构造一个对象.例如,可以通过以下方式定义复制赋值运算符
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;
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,首先使用析构函数的显式调用销毁当前对象,然后在此地址处使用复制构造函数创建新对象.
也就是说,这个新运算符不会分配新的内存范围.它使用已经分配的内存.
此示例取自C++标准.至于我,我不会返回一个const对象.将运算符声明为更正确
C& C::operator=( const C& other);
Run Code Online (Sandbox Code Playgroud)