Placement - a new STL container and its subsequent destruction

This code implements an unlimited union that provides access by name and index to any of its three members.

Since it is std::stringnontrivially constructed and destroyed, I need to provide a special constructor and destructor for union.

#include <iostream>
#include <string>

using namespace std ;

union MyUnion{
    string parts[3] ;
    struct{ string part1, part2, part3 ; } ;

    MyUnion(){
        new(parts+0) string ; //constructs the 3 strings in-place
        new(parts+1) string ;
        new(parts+2) string ;
    }
    ~MyUnion(){
        parts[0].~string() ; //calls string destructor
        parts[1].~string() ;
        parts[2].~string() ;
    }
} ;

int main(){

    MyUnion u ;

    u.part1 = "one" ; //access by name
    u.part2 = "two" ;
    u.part3 = "three" ;

    cout << u.parts[0] << endl ; //access by index
    cout << u.parts[1] << endl ;
    cout << u.parts[2] << endl ;
}

This example compiles and works fine (apparently), but my questions are:

  • Can this be done?
  • Can I be sure that there will be no memory leaks?
  • What if the constructor stringthrows an exception? Does it need to be caught so as not to try to destroy an object that has never been constructed?

Note

The code compiles in VC2015, which supports unnamed structures. Please ignore this item.

+6
2

?

. -, , :

(9.3) struct T1 m T2 , m T1 T2; , T1.

-, :

( 9) - [...]

std::string .

+2

?

, . , , undefined .

, , (9.3 Unions), , (9.2 /20), . , -.

, , int x[3]; struct {int x0, x1, x2};. , x2 x[2] .

0

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


All Articles