相关疑难解决方法(0)

const成员和赋值运算符.如何避免未定义的行为?

回答了关于std :: vector of objects和const-correctness的问题,得到了不应有的 downvote和关于undefined行为的评论.我不同意,因此我有一个问题.

考虑使用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
}; 
Run Code Online (Sandbox Code Playgroud)

我想要一个赋值运算符,但我不想const_cast在下面的代码中使用其中一个答案:

A& operator=(const A& assign) 
{ 
    *const_cast<int*> (&c)= assign.c;  // very very bad, IMHO, it is undefined behavior
    return *this; 
} 
Run Code Online (Sandbox Code Playgroud)

我的解决方案是

A& operator=(const A& right)  
{  
    if (this == &right) return *this;  
    this->~A() 
    new (this) A(right); …
Run Code Online (Sandbox Code Playgroud)

c++ const undefined-behavior assignment-operator

33
推荐指数
3
解决办法
2万
查看次数