CWG Issue 1404 (original) (raw)

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

2025-04-13


1404. Object reallocation in unions

Section: 11.5 [class.union]Status: openSubmitter: Nikolay IvchenkovDate: 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 typeN. If M has a non-trivial destructor andN has a non-trivial constructor (for instance, if they declare or inherit virtual functions), the active member ofu can be safely switched from m to nusing 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.