Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a union consisting of const-qualified variant members lead to having no defaulted default constructor?

Tags:

The standard draft as of N4567 suggests that a defaulted default constructor is defined as deleted if—according to 12.1, paragraph 4:

X is a union and all of its variant members are of const-qualified type (or array thereof),

In other words, it is equivalent to saying that, if one of its variant members is not const-qualified, the above rule does not apply. My question is:

  • What's so special about having all of its members const-qualified (as compared to the opposite situation where at least one of those is not const-qualified), and in what perspective is it deeply related to a defaulted default constructor?
like image 400
b1sub Avatar asked Jun 04 '16 13:06

b1sub


1 Answers

Suppose you have a union with only const members:

union Foo {
    const int x;
    const double y;
}

A default constructor would have to decide which of the members to initialize and become the active member. Once created you cannot change the value of any member (they are all const) thus you could also not change which is the active member. Thus such a construct would be rather useless as union.

On the other hand, if one member is not const:

union Bar {
    int x;
    const double y;
    Bar() : y(10.0) {}
}

a default constructor could make sense, because you can still later change the active member via

Bar b;
b.x = 10;
like image 197
463035818_is_not_a_number Avatar answered Oct 13 '22 22:10

463035818_is_not_a_number