title: Passing by reference - why is this destructor being called?
body: <p>I could not find (of the many questions on destructor calling topics) any that were exactly the same as my situation.</p>
  
  <p>Why is the destructor being called when the parameter passed is a reference? I put comments (mostly in main) under the lines of code where I thought the output was executing from.</p>
  
  <pre><code>struct X { // simple test class
     int val;
  
     void out(const std::string&amp; s, int nv)
     {
        std::cerr &lt;&lt; this &lt;&lt; "–&gt;" &lt;&lt; s &lt;&lt; ": " &lt;&lt; val &lt;&lt; " (" &lt;&lt; nv &lt;&lt; ")\n";
     }
  
     // default constructor
     X() { 
        out("X()", 0); 
        val = 0; 
     } 
  
     X(int v) { 
        val = v; 
        out("X(int)", v); 
     }
  
     // copy constructor
     X(const X&amp; x) {
        val = x.val; 
        out("X(X&amp;) ", x.val); 
     } 
  
     // copy assignment
     X&amp; operator=(const X&amp; a)
     {
        out("X::operator=()", a.val); 
        val = a.val; 
        return *this;
     }
  
     // Destructor
     ~X() { 
        out("~X()", 0); 
     }
  };
  
  X glob(2); // a global variable
  // Output Line 1: X(int): 2 (2)
  
  X copy(X a) { 
     return a; 
  }
  </code></pre>
  
  <p><code>main</code> Function:</p>
  
  <pre><code>    int main()
  {
     X loc{ 4 }; // local variable
        // Output Line 2: X(int): 4 (4)
        // ^from X(int v) function
     X loc2{ loc }; // copy construction
        // Output Line 3: X(X&amp;) : 4 (4)
        // ^from X(const X&amp; x) function
     loc = X{ 5 }; // copy assignment 
        // Output Line 4: X(int): 5 (5)
        // ^from X(int v) function
        // Output Line 5: X::operator=(): 4 (5)
        // ^from the '=' operator overload
        // Output Line 6: ~X(): 5 (0) - ???
     loc2 = copy(loc); // call by value and return 
        // Or does Output Line 6 result from here?
     .
     .
     .
  }
  </code></pre>
  
  <p>1) Is this destructor is being called because of <code>loc = X{ 5 }; // copy assignment</code> or the line after: <code>loc2 = copy(loc); // call by value and return</code>?</p>
  
  <p>2) Why is it being called? From what I've read, destructors are only called when:</p>
  
  <pre><code>a) names go out of scope
  b) program terminates
  c) "delete" is used on a pointer to an object
  </code></pre>
  
  <p>I know its not 'b' or 'c' so it has to be because something is going out of scope. But I do not think a reference going out of scope from the copy assignment function does this.</p>