The rationale for active union members

C ++ associations are more restrictive than C because they introduce the notion of an "active member" (last assigned) as the only safe access. The way I see it, such union behavior is purely negative. Can someone explain what happened if you have this limitation?

+4
source share
1 answer

Short answer

In C, joining is just a matter of how to interpret data stored in a specific place. Data is passive.

++ . , . () (, , ), , . : , .

:

union U {
    string s;
    int i;

    // due to string, I need to define constructor and destructor
    U (string s) : s(s) { cout << "s is active"<<endl;}
    U (int i) : i(i) { cout << "i is active"<<endl;}
    U() : s() { cout << "s is active by default" <<endl; }
    ~U() { cout << "delete... but what ?"<<endl; }
};

, :

U u("hello"); 

s. memeber :

u.s += ", world";  
cout << u.s <<endl;

, , ( ++). , , :

u.i=0;  // ouch!!! this is not the active member : what happens to the string ?  

undefined ( s , ). . , i, :

u.s="goodbye";  // thinks that s is an active valid string which is no longer the case 

, , s . s , undefined.

,

?

:

M N (, ), u m n, :

u.m.~M();
new (&u.n) N;

, :

u.s.~string(); // properly end the life of s
u.i=0;  // this is now the active member   
           // no need to end life of an int, as it has a trivial destructor 
new (&u.s) string("goodbye");  // placement new  
cout << u.s <<endl;    

, ()

+1

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


All Articles