Behavior of self-assignment with const ref parameter

前端 未结 1 365
一整个雨季
一整个雨季 2021-01-12 06:47

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

1条回答
  •  生来不讨喜
    2021-01-12 07:14

    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.

    0 讨论(0)
提交回复
热议问题