title: C++: Destructor in Union-Like Struct With Non Trivial Members
body: <p>I have the following union-like struct</p>
  <pre class="lang-cpp prettyprint-override"><code>struct MyStruct {
      enum {A, B} tag;
  
      union {
          int option_1;
  
          struct {
              unordered_map&lt;string, into&gt; map;
              int number;
          }option_2;
      };
  
      MyStruct(int x) : tag(A) {
          option_1 = x;
      }
  
      MyStruct(unordered_map&lt;string, int&gt; &amp;map, int x) : tag(B) {
          new (&amp;option_2.map) unordered_map&lt;string, int&gt;(std::move(map));
          option_2.number = x;
      }
  
      ~MyStruct() {
      // Some code here
      }
  };
  </code></pre>
  <p>The <code>unordered_map</code> makes the union non trivial. Since I'm calling <code>new</code> in one of the the constructors I would need to free the memory for the map once I'm done with the struct. So I thought I should call <code>delete</code> in the destructor.</p>
  <pre class="lang-cpp prettyprint-override"><code>~MyStruct () {
      if (tag == B) {
          delete &amp;option_2.map;
      }
  }
  </code></pre>
  <p>But this gives me runtime errors saying I can't call free on the pointer. I then simply tried to free the map by setting the other Union member, and it seemed to work (trying to access the map after the struct goes out of scope results in a seg fault).</p>
  <pre class="lang-cpp prettyprint-override"><code>~MyStruct () {
      option_1 = 0;
  }
  </code></pre>
  <p>My question is why doesn't my first attempt at a destructor work, and is the second attempt at a destructor the best practice here?</p>