【发布时间】:2014-09-10 05:07:25
【问题描述】:
标准引用如下示例(3.8/7 N3797):
struct C
{
int i;
void f();
const C& operator=( const C& );
};
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
f(); // well-defined
}
return *this;
}
C c1;
C c2;
c1 = c2; // well-defined
c1.f(); // well-defined; c1 refers to a new object of type C
如果我们如下实现operator=,是否存在UB:
const C& C::operator=( const C& other)
{
if ( this != &other )
{ // Note that there is no more explcicitly destructor call,
// since at the time of memory reusing the lifetime of
// this is still going on
new (this) C(other); // new object of type C created
f(); // well-defined
}
return *this;
}
相关引用是:
如果,在对象的生命周期之后已经结束并且在存储之前 被占用的对象被重用或释放,一个新的对象被 在原始对象占用的存储位置创建,a 指向原始对象的指针,引用的引用 到原始对象,或者原始对象的名称将 自动引用新对象,并且一旦生命周期 新对象已启动,可用于操作新对象
没有规则:“在存储位置创建一个新对象,而不是一个对象占用”。
同时,我们有一个适合const 对象的规则。很明显:
第 3.8/9 节:
在 const 对象的存储位置创建一个新对象 静态、线程或自动存储持续时间占用,或者,在 这种 const 对象在其之前占用的存储位置 生命周期结束会导致未定义的行为。
【问题讨论】:
标签: c++ constructor