オブジェクトの std::vector と const-correctnessに関する質問に回答し、未定義の動作に関するコメントを受け取りました。同意できないので、質問があります。
const メンバーを持つクラスを考えてみましょう。
class A {
public:
const int c; // must not be modified!
A(int c) : c(c) {}
A(const A& copy) : c(copy.c) { }
// No assignment operator
};
const_cast
代入演算子が必要ですが、回答の1つから次のコードのように使用したくありません。
A& operator=(const A& assign)
{
*const_cast<int*> (&c)= assign.c; // very very bad, IMHO, it is undefined behavior
return *this;
}
私の解決策は
// Custom-defined assignment operator
A& operator=(const A& right)
{
if (this == &right) return *this;
// manually call the destructor of the old left-side object
// (`this`) in the assignment operation to clean it up
this->~A();
// use "placement new" syntax to copy-construct a new `A`
// object from `right` into left (at address `this`)
new (this) A(right);
return *this;
}
未定義の動作 (UB) はありますか?
UB なしのソリューションは何でしょうか?