title: C++ Template class constructor calling destructor of member variable
body: <p>I have a template class that holds a pair of type <code>T</code> with a single constructor that accepts two parameters of type <code>T</code>.</p>
  <pre><code>template&lt;class T&gt;
  class Foo {
      T first;
      T second;
  public:
      Foo(T first, T second) {
          if (first &lt; second) {
              this-&gt;first = first;
              this-&gt;second = second;
          } else {
              throw std::invalid_argument(&quot;First cannot be greater than second.&quot;);
          }
      }
      ...
  }
  </code></pre>
  <p>and I pass two objects of my own class <code>Bar</code> to it in the main.  Here is what <code>Bar</code> looks like:</p>
  <pre><code>class Bar{
  public:
      char* name; // I am required to use c style strings.
      Gender gen;
  public:
      // need this empty constructor or the compiler complains in main
      Bar() {
      }
      Bar(const char* s, Gender g);
      Bar(const Bar&amp; bar) {
          name = bar.name;
          gen = bar.gen;
      }
      ~Bar();
  }
  ...
  // Bar's destructor looks like this:
  Bar::~Bar() {
      delete[] name;
  }
  </code></pre>
  <p>and this is what I do in main:</p>
  <pre><code>try {
      Bar b1(&quot;Mary&quot;, Gender::female);
      Bar b2(&quot;George&quot;, Gender::male);
  
      Foo&lt;Bar&gt; pair(b1, b2);
  
      // Foo's member's, b1 and b2 are already destroyed at this point after its constructor.
      // If I put cout statements in the destructor of Bar, they will be printed before the below cout.
  
      std::cout &lt;&lt; &quot;end of try&quot; &lt;&lt; std::endl;
  } catch (const std::invalid_argument&amp; ia) {
      std::cerr &lt;&lt; &quot;Invalid argument: &quot; &lt;&lt; ia.what() &lt;&lt; std::endl;
  }
  </code></pre>
  <p>My question is, why does the constructor of <code>Foo</code> delete <code>first</code> and <code>second</code> right after the end of its constructor?  If I follow what happens with the debug tool, <code>Foo</code> works as planned but then deletes <code>first</code> and <code>second</code> as soon as it hits the ending parenthesis of its constructor.  Why? Why did these member variable go out of scope?</p>