const member and assignment operator. How to avoid the undefined behavior?

前端 未结 8 1692
别跟我提以往
别跟我提以往 2020-12-05 17:14

I answered the question about std::vector of objects and const-correctness, and received a comment about undefined behavior. I do not agree and therefore I have a question.<

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 17:51

    In absence of other (non-const) members, this doesn't make any sense at all, regardless of undefined behavior or not.

    A& operator=(const A& assign) 
    { 
        *const_cast (&c)= assign.c;  // very very bad, IMHO, it is UB
        return *this; 
    }
    

    AFAIK, this is no undefined behavior happening here because c is not a static const instance, or you couldn't invoke the copy-assignment operator. However, const_cast should ring a bell and tell you something is wrong. const_cast was primarily designed to work around non const-correct APIs, and it doesn't seem to be the case here.

    Also, in the following snippet:

    A& operator=(const A& right)  
    {  
        if (this == &right) return *this;  
        this->~A() 
        new (this) A(right); 
        return *this;  
    }
    

    You have two major risks, the 1st of which has already been pointed out.

    1. In presence of both an instance of derived class of A and a virtual destructor, this will lead to only partial reconstruction of the original instance.
    2. If the constructor call in new(this) A(right); throws an exception, your object will be destroyed twice. In this particular case, it won't be a problem, but if you happen to have significant cleanup, you're going to regret it.

    Edit: if your class has this const member that is not considered "state" in your object (i.e. it is some sort of ID used for tracking instances and is not part of comparisons in operator== and the like), then the following might make sense:

    A& operator=(const A& assign) 
    { 
        // Copy all but `const` member `c`.
        // ...
    
        return *this;
    }
    

提交回复
热议问题