DaBler DaBler - 3 years ago 223
C++ Question

Placement new and assignment of class with const member

Why is that undefined behaviour?

struct s
const int id; // <-- const member

s(int id):

s& operator =(const s& m) {
return *new(this) s(m); // <-- undefined behavior?

(Quote from the standard would be nice).

This question arose from this answer.

Answer Source

There is nothing that makes the shown code snippet inherently UB. However, it is almost certain UB will follow immediately under any normal usage.

From [basic.life]/8 (emphasis mine)

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 storage for the new object exactly overlays the storage location which the original object occupied, and

  • the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and

  • the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and

  • the original object was a most derived object of type T and the new object is a most derived object of type T (that is, they are not base class subobjects).

Since there is a const member in s, using the original variable after a call to operator= will be UB.

s var{42};
var = s{420};         // OK
do_something(var.id); // UB! Reuses s through original name
do_something(std::launder(&var)->id);  // OK, this is what launder is used for
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download