title: Calling the destructor for matched type in boost-variant
body: <p>I'm using boost-variant, and when switching types in the variant I want to ensure the destructor is called.  The following code "works" but i'm not sure why.  I feel like it should segfault as it's calling a delete on an uninitialized pointer.  Is there some boost-variant magic going on behind the scenes?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;boost/variant.hpp&gt;
  using namespace std;
  
  class A
  {
      public:
          A() {}
          virtual ~A() { cout &lt;&lt; "Destructing A" &lt;&lt; endl; }
  };
  
  class B
  {
      public:
          B() {}
          virtual ~B() { cout &lt;&lt; "Destructing B" &lt;&lt; endl; }
  };
  
  typedef boost::variant&lt;A*, B*&gt; req;
  
  class delete_visitor : public boost::static_visitor&lt;void&gt;
  {
      public:
          inline void operator() (A *a) const
          {
              cout &lt;&lt; "Will destruct A" &lt;&lt; endl;
              delete a;
          }
          inline void operator() (B *b) const
          {
              cout &lt;&lt; "Will destruct B" &lt;&lt; endl;
              delete b;
          }
  };
  class Wrapper
  {
      public:
          Wrapper(int s) {
              setBackend(s);
          }
          virtual ~Wrapper() {
              // cleanup
              boost::apply_visitor(delete_visitor(), my_pick);
          }
          void setBackend(int s)
          {
              // make sure if we already have put something in our variant, we clean it up
              boost::apply_visitor(delete_visitor(), my_pick);
              if(s == 0)
                  my_pick = new A();
              else
                  my_pick = new B();
          }
  
      private:
          req my_pick;
  };
  
  int main()
  {
      Wrapper *w = new Wrapper(0);
      w-&gt;setBackend(1);
      delete w;
      return 0;
  }
  </code></pre>
  
  <p>The following is what I get for output:</p>
  
  <pre><code>Will destruct A
  Will destruct A
  Destructing A
  Will destruct B
  Destructing B
  </code></pre>