【发布时间】:2013-04-02 16:15:06
【问题描述】:
很多类的赋值运算符 (operator=) 与析构函数中的代码相同,但与复制构造函数的代码非常相似。
那么以这种方式实现分配是个好主意吗?
Point& operator=(const Point& point)
{
if(&point != this)
{
//Call the destructor
this->~Point();
//Make the placement new
//Assignment is made because some compilers optimise such code as just
// new Point;
Point* p_n = new (this) Point(point);
//We where placing in this place so pointers should be equal
assert(p_n == this);
}
return *this;
}
【问题讨论】:
-
如果你这样做,一定要先检查
&point != this! -
另外,这段代码也不是异常安全的——如果
new (this) Point(point)出现异常,将会造成双重破坏。只需使用copy and swap idiom。 -
新展示位置能否引发异常?
-
@Seagull,Point 的 ctor(或正在构造的类型)可以抛出。
-
@Seagull,“我确信从构造函数中抛出是一件可怕的事情” - 从 构造函数 中抛出是一件很棒的事情!它允许建立对象不变量和use it easily。
标签: c++ new-operator variable-assignment placement-new