Put a class with user-defined constructors in a union

class Foo { Foo(int val) { /* Do some initialization */ } Foo() { /* Do nothing */ } }; union Bar { Foo foo; }; 

This code generates this error:

error C2620: member of Bar :: foo of the Bar association has a user-defined constructor or non-trivial default constructor

I understand why you chose this error if the constructor really did something, but the constructor here does not accept any parameters and does nothing. Is there a way I can fill this class with union? I had to resort to using char foo[sizeof(Foo)] and would like to make a cleaner solution.

+4
source share
4 answers

Originally from this question:

Initializing a union with a non-trivial constructor :

From C ++ 03, 9.5 Unions, pg 162

A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. The union should not have base classes. A join should not be used as a base class. A class object with a nontrivial constructor (12.1) is a nontrivial copy constructor (12.8), a nontrivial destructor (12.4) or a nontrivial copy assignment operator (13.5.3, 12.8) cannot be a member of a union, as well as an array of such objects

So, your class is forbidden to be a member of the union.

+6
source

This is prohibited in the C ++ 03 standard.

If objects with user-defined default constructors were allowed in the union, the compiler could not decide which constructor to use, because everyone belongs to the same place in memory. Therefore, objects with user-defined constructors are not allowed in unions.

The compiler ignores the fact that your constructor does nothing, because it can be defined elsewhere than in a union.

You can get away with C ++ 0x constructor() = default;

+3
source

Standard specialists are likely to answer this question more accurately than I do, but if I remember correctly, union members should be of type POD.

Use boost::variant if you want to use non-POD classes inside the union.

+1
source

If your class has a user-defined constructor, destructor or copy constructor, or assignment operator, then it cannot be inside the Union.

0
source

All Articles