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

前端 未结 8 1693
别跟我提以往
别跟我提以往 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:56

    According to the newer C++ standard draft version N4861 it seems to be no longer undefined behaviour (link):

    If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if the original object is transparently replaceable (see below) by the new object. An object o1 is transparently replaceable by an object o2 if:

    • the storage that o2 occupies exactly overlays the storage that o1 occupied, and
    • o1 and o2 are of the same type (ignoring the top-level cv-qualifiers), and
    • o1 is not a complete const object, and
    • neither o1 nor o2 is a potentially-overlapping subobject ([intro.object]), and
    • either o1 and o2 are both complete objects, or o1 and o2 are direct subobjects of objects p1 and p2, respectively, and p1 is transparently replaceable by p2.

    Here you can find only "o1 is not a complete const object" regarding const, which is true in this case. But of course you have to ensure that all other conditions are not violated, too.

提交回复
热议问题