This is an unofficial snapshot of the ISO/IEC JTC1 SC22 WG21 Core Issues List revision 116a. See http://www.open-std.org/jtc1/sc22/wg21/ for the official list.

2024-12-19


1404. Object reallocation in unions

Section: 11.5  [class.union]     Status: drafting     Submitter: Nikolay Ivchenkov     Date: 2011-10-19

According to 11.5 [class.union] paragraph 4,

[Note: In general, one must use explicit destructor calls and placement new operators to change the active member of a union. —end note] [Example: Consider an object u of a union type U having non-static data members m of type M and n of type N. If M has a non-trivial destructor and N has a non-trivial constructor (for instance, if they declare or inherit virtual functions), the active member of u can be safely switched from m to n using the destructor and placement new operator as follows:

  u.m.~M();
  new (&u.n)  N;

end example]

This pattern is only “safe” if the original object that is being destroyed does not involve any const-qualified or reference types, i.e., satisfies the requirements of 6.7.4 [basic.life] paragraph 7, bullet 3:

Although paragraph 4 of 11.5 [class.union] is a note and an example, it should at least refer to the lifetime issues described in 6.7.4 [basic.life].

Additional note (October, 2013):

See also issue 1776, which suggests possibly changing the restriction in 6.7.4 [basic.life]. If such a change is made, this issue may become moot.