【发布时间】:2018-05-08 11:44:35
【问题描述】:
为什么这是未定义的行为?
struct s
{
const int id; // <-- const member
s(int id):
id(id)
{}
s& operator =(const s& m) {
return *new(this) s(m); // <-- undefined behavior?
}
};
(引用标准会很好)。
这个问题来自this answer。
【问题讨论】:
-
const int id;表示id的值永远不会改变。然后你改变它? -
@BoPersson:另一种观点是我在同一个位置创建了一个新对象。
-
我清楚地记得这是合法的。 @BoPersson
const仅适用于对象的生命周期。 -
@YSC 未调用析构函数不是未定义的行为。对无效对象调用析构函数是。
-
@YSC 如果析构函数是微不足道的(就像在这种情况下),那么不调用它是合法的。 timsong-cpp.github.io/cppwp/basic.life#5.sentence-1
标签: c++ constants language-lawyer assignment-operator placement-new