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
const int id;
says that the value ofid
will never change. And then you change it? – Evanstonconst
only applies to the lifetime of the object. – Rogersconst
, because I don't know if timsong-cpp.github.io/cppwp/basic.life#10 seems to apply. – Trenatrenailconst
objects, not object withconst
members, is it not? – Smaltite[basic.life]/9
, it says explicitly it's ok? – Smaltite