You do not have Undefined Behavior regarding switch_me
function: you do not access object in any way after destruction, and next access happens on new object. You might have UB if you save pointer and reference to C
object returned vy operator->
and use it after call to switch_me
per 3.8/7:
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 (1.8) of
type T and the new object is a most derived object of type T (that
is, they are not base class subobjects).
You do have UB in other place, namely, your storage. It has weaker alignment than object you want to place in it, and that can cause alignment issues. Use alignas
keyword to specify desired alignment:
alignas(C1) alignas(C2) char storage[std::max(sizeof(C1),sizeof(C2))];
If two alignment specifiers are applied to same declaration, larger is used.