Title
Trivial copyability and unions with non-trivial members
Status
open
Section
11.2 [class.prop]
Submitter
Daveed Vandevoorde

Created on 2020-11-30.00:00:00 last changed 10 months ago

Messages

Date: 2020-11-30.00:00:00

According to 11.2 [class.prop] paragraph 1,

A trivially copyable class is a class:

  • that has at least one eligible copy constructor, move constructor, copy assignment operator, or move assignment operator (11.4.4 [special], 11.4.5.3 [class.copy.ctor], 11.4.6 [class.copy.assign]),

  • where each eligible copy constructor, move constructor, copy assignment operator, and move assignment operator is trivial, and

  • that has a trivial, non-deleted destructor (11.4.7 [class.dtor]).

This definition has surprising effects in a union whose members are not trivial. For example:

  struct S {
    S& operator=(const S&);
  };
  union U {
    S s;
  }; 

In this case, S is not trivially copyable because its assignment operator is non-trivial, although its copy constructor is trivial. U, however, is trivially copyable because its assignment operator is not eligible (11.4.4 [special] paragraph 6) because it is deleted, but its copy constructor is trivial, thus satisfying the second bullet.

It is unclear why, for example, a complete object of type S cannot be memcpyed but such an object can be memcpyed when embedded in a union.

There is implementation divergence in the handling of this example.

History
Date User Action Args
2020-11-30 00:00:00admincreate