title: delete mother object if exception thrown in member
body: <p>I have the following issue:</p>
  
  <p>I want to delete a mother object if an exception is thrown inside the constructor of one of its members.
  How do I do that?</p>
  
  <p>The following does NOT what I want. Just you have something to refer to...</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  struct A
  {
  
      A(int i)
      :mem(0)
      {
          try{
              if(i &gt; 9) throw 0;
          }catch(int x) { std::cout &lt;&lt; "mem max size 9\n"; return;}
          mem = i;
      }
  
      int mem;
  };
  
  struct B
  {
      B(int i)
      :mem(i)
      {
      }
  
      const A mem;
  
  };
  
  int main()
  {
  
      B b1(2);
      B b2(10);
  
      std::cout &lt;&lt; "b1: " &lt;&lt; b1.mem.mem &lt;&lt; std::endl;
      std::cout &lt;&lt; "b2: " &lt;&lt; b2.mem.mem &lt;&lt; std::endl;
  
  }
  
  //~ output:
  //~ mem max size 9
  //~ b1: 2
  //~ b2: 0
  </code></pre>
  
  <h1>Edit</h1>
  
  <p>Following <a href="http://gotw.ca/gotw/066.htm" rel="nofollow">this link</a> I changed my code as follows</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  struct A
  {
  
      A(int i)
      :mem(0)
      {
          if(i &gt; 9) throw 0;
          else mem = i;
      }
  
      int mem;
  };
  
  struct B
  {
      B(int i)
      try
      :mem(i)
      {
      }
      catch(int e)
      {
          std::cerr &lt;&lt; "Error #" &lt;&lt; e &lt;&lt; std::endl;
      }
  
      const A mem;
  };
  
  int main()
  {
      B b1(2);
      B b2(10);
  }
  
  //~ output:
  //~ Error #0
  //~ terminate called after throwing an instance of 'int'
  //~ Aborted
  </code></pre>
  
  <p>But, I don't want the program to abort... how can I prevent that?</p>
  
  <p>If I do it like this, the program does not get aborted but the B object is being constructed despite the exception...</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  struct A
  {
  
      A(int i)
      :mem(0)
      {
          try
          {
              if(i &gt; 9) throw 0;
          }
          catch(int e)
          {
              std::cerr &lt;&lt; "A Error #" &lt;&lt; e &lt;&lt; std::endl; return;
          }
           mem = i;
      }
  
      int mem;
  };
  
  struct B
  {
      B(int i)
      try
      :mem(i)
      {
      }
      catch(int e)
      {
          std::cerr &lt;&lt; "Error #" &lt;&lt; e &lt;&lt; std::endl;
      }
  
      const A mem;
  };
  
  int main()
  {
  
      B b1(2);
      B b2(10);
  
      std::cout &lt;&lt; "b1: " &lt;&lt; b1.mem.mem &lt;&lt; std::endl;
      std::cout &lt;&lt; "b2: " &lt;&lt; b2.mem.mem &lt;&lt; std::endl;
  
  }
  
  //~ A Error #0
  //~ b1: 2
  //~ b2: 0
  </code></pre>
  
  <p>and if I re-throw in the catch in A the program gets aborted again...</p>