Behavior of self-assignment with const ref parameter

怎甘沉沦 提交于 2019-12-09 03:06:32

问题


I stumbled upon some very old code which has a class with a defined copy assignment operator which takes its parameter as a const reference, but also does not check for self-assignment, so essentially:

struct A
{
    int q;
    A(): q(3) {}

    A& operator=(const A& a)
    {
        q = a.q;
        return *this;
    }
};

What is the behavior of this assignment operator when an instance of A is assigned to itself? I would assume this causes problems as it "breaks" the constness of the paramater, any compiler could assume that the parameter is not changed and optimize based on this.

However neither clang nor gcc emit a warning, and the program runs fine. This also works if I explicitly change the value of q to 4 before the assignment in the assignment operator.


回答1:


Binding an object to a const reference doesn't make it const all of a sudden. The const there only indicates that the function cannot modify the parameter via a. It doesn't mean that the referred to object has to be const itself.

Since *this and a can legally alias the same object, there's no risk in such code. The compiler cannot make wild assumptions about aliasing.

Self-assignment is only an issue when the object state can be left somehow corrupted if the assignment operator doesn't run to completion, or releases a resource it then tries to copy from "other". Your example has no risk of that happening. In general however, one should be mindful of exceptions potentially being thrown and ownership of resources.



来源:https://stackoverflow.com/questions/49146481/behavior-of-self-assignment-with-const-ref-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!