C ++ 11 unlimited unions example

I read http://www.stroustrup.com/C++11FAQ.html#unions

but I can not compile this example:

union U1 {
    int m1;
    complex<double> m2; // ok
};

union U2 {
    int m1;
    string m3;  // ok
};

U1 u;       // ok
u.m2 = {1,2};   // ok: assign to the complex member

Results in:

main.cpp:85:8: error: use of deleted function 'U1::U1()'
     U1 u;       // ok
        ^   
main.cpp:75:11: note: 'U1::U1()' is implicitly deleted because the default definition would be ill-formed:
     union U1 {
           ^   
main.cpp:77:25: error: union member 'U1::m2' with non-trivial 'constexpr std::complex<double>::complex(double, double)'
         complex<double> m2; // ok
                         ^   
main.cpp:86:5: error: 'u' does not name a type
     u.m2 = {1,2};   // ok: assign to the complex member
     ^   
make: *** [main.o] Error 1

Questions:

I thought that in an unlimited join, the first element would be constructed if the default manual constructor was not set. Is this true and how to write a working example?

The following file will also not compile:

class Y
{   
    public:
        constexpr Y() {}
};  

union X
{   
    int a;
    float b;
    Y x;
    //X(){}
};  

X x;

int main(){}

The same error messages:

main.cpp:112:7: error: use of deleted function 'X::X()'
     X x;
       ^   
main.cpp:104:11: note: 'X::X()' is implicitly deleted because the default definition would be ill-formed:
     union X
           ^   
main.cpp:108:11: error: union member 'X::x' with non-trivial 'constexpr Y::Y()'
         Y x;
           ^   
make: *** [main.o] Error 1
+4
source share
2 answers

In the reference standard [class.union] in paragraph 2 (in the notes) the following is reported:

- ( ), (10.3) . . . , . -. [: - union (12.1), (12.8), (12.8), (12.8), (12.8) (12.4), ​​ (8.4.3) . - ]

, .

3 :

union U {
int i;
float f;
std::strings;
};

:

std::string (21.3) -, U , / , / . U - .


:

, , ; . .

. std::string std::complex , . .

+4

m2 . " " , , , deleted.

" , , , ; . "," ++ ", . 215.

union U { int m1;
complex<double> m2; // complex has a constructor
string m3; // string has a constructor (maintaining a serious invariant) 
};

", U ". ( )

0

Source: https://habr.com/ru/post/1534377/


All Articles