这是什么语法- new (this) T();
what is this syntax - new (this) T();
我遇到了这样的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);
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 为什么使用 "this" 指针调用派生成员函数?
- 如果"new int"返回"int*",那么为什么"new int[n]"不返回"int**"?
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 重载运算符new[]的行为取决于析构函数
- C++错误:"error: int aaa::bbb is protected within this context"
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 过载'operator new'如何导致无限循环?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- Codelite C++ new project
- 在类c++中使用new声明数组
- 关于C++中具有多重继承"this"指针的说明
- g++用户定义的动态链接库上的全局new和delete运算符
- 在noexcept 规范中是否允许使用"this"?
- 重载new返回的值与this不匹配
- 删除虚拟派生类的this和位置new
- 这是什么语法- new (this) T();
- 我可以在运算符=中使用placement new(this)吗
- delete this + memmove(this,new A(),sizeof(A))安全吗?这是个坏主意吗?
- new (this)是什么意思?