Title
Object reallocation in unions
Status
drafting
Section
11.5 [class.union]
Submitter
Nikolay Ivchenkov

Created on 2011-10-19.00:00:00 last changed 136 months ago

Messages

Date: 2013-10-15.00:00:00

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.

Date: 2011-10-19.00:00:00

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:

  • 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

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].

History
Date User Action Args
2013-10-14 00:00:00adminsetmessages: + msg4628
2012-02-27 00:00:00adminsetstatus: open -> drafting
2011-10-19 00:00:00admincreate