This code implements an unlimited union that provides access by name and index to any of its three members.
Since it is std::string
nontrivially 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 ;
new(parts+1) string ;
new(parts+2) string ;
}
~MyUnion(){
parts[0].~string() ;
parts[1].~string() ;
parts[2].~string() ;
}
} ;
int main(){
MyUnion u ;
u.part1 = "one" ;
u.part2 = "two" ;
u.part3 = "three" ;
cout << u.parts[0] << endl ;
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
string
throws 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.