title: Placement-new an STL container and destroying it safely afterwards
body: <p>This code implements an unrestricted union which provides access by name and by index to any of its three members.</p>
  <p>Since <code>std::string</code> is non-trivially constructed and destroyed, I need to provide special constructor and destructor for the <code>union</code>.</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  
  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's destructor
          parts[1].~string() ;
          parts[2].~string() ;
      }
  } ;
  
  int main(){
      
      MyUnion u ;
      
      u.part1 = &quot;one&quot; ; //access by name
      u.part2 = &quot;two&quot; ;
      u.part3 = &quot;three&quot; ;
  
      cout &lt;&lt; u.parts[0] &lt;&lt; endl ; //access by index
      cout &lt;&lt; u.parts[1] &lt;&lt; endl ;
      cout &lt;&lt; u.parts[2] &lt;&lt; endl ;
  }
  </code></pre>
  <p>This example compiles and works fine (seemingly), but my questions are:</p>
  <ul>
  <li>Is it safe to do this?</li>
  <li>Can I be sure that there will be no memory leaks?</li>
  <li>What if <code>string</code>'s constructor throws an exception? Does that need to be caught so as to not try to destroy an object that was never constructed?</li>
  </ul>
  <h3>Note</h3>
  <p>The code compiles in VC2015, which does support unnamed structs. Please disregard that detail.</p>