title: C++ : copy-and-swap idiom, alternative constructor
body: <p>NB: This question follows <a href="https://stackoverflow.com/questions/18134224/c-tree-class-constructor-copy-memory-leak">a previous one</a>, I hope it is okay to still ask it as a new question.</p>
  
  <p>I am trying to implement the "three and a half big rule" (copy-and-swap idiom) for a tree class, which looks like this:</p>
  
  <pre><code>class Tree
  {
      friend void swap(Tree &amp;first, Tree &amp;second); // Swap function
  
  public:
      Tree(const double &amp;a, const double &amp;b, int depth); // Public constructor (derived from the default (private) constructor)
      Tree(const Tree &amp;other); // Copy constructor
      ~Tree(); // Destructor
      Tree &amp; operator=(Tree other); // Copy-assignement operator
  
  
  private:        
      Tree(double *a, double *b, int depth, int maxDepth); // Default (private) constructor
  
      double *a, *b;
      int depth, maxDepth;    
      Tree *leftChild, *rightChild;
  };
  </code></pre>
  
  <p>I have been trying to follow <a href="https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom">this guideline</a>. Here is what my copy-assignment operator looks like:</p>
  
  <pre><code>Tree &amp; Tree::operator=(Tree other)
  {
      swap(*this, other);
      return *this;
  }
  </code></pre>
  
  <p>I am having a hard time getting my public constructor to work. Someone suggested I do something like:</p>
  
  <pre><code>Tree::Tree(const double &amp;a, const double &amp;b, int depth)
  {
      double aTemp(a), bTemp(b);
      swap(*this, Tree(&amp;aTemp, &amp;bTemp, depth, depth));
  }
  </code></pre>
  
  <p>I am not sure this idea works. In any case I get the following error from the compiler:</p>
  
  <pre><code>invalid initialization of non-const reference of type 'Tree&amp;' from an rvalue of type 'Tree'
  in passing argument 2 of 'void swap(Tree&amp;, Tree&amp;)'
  </code></pre>
  
  <p>I tried the following idea instead, which I thought would work:</p>
  
  <pre><code>Tree::Tree(const double &amp;a, const double &amp;b, int depth)
  {
      double aTemp(a), bTemp(b);
      *this = Tree(&amp;aTemp, &amp;bTemp, depth, depth);
  }
  </code></pre>
  
  <p>But it does not seem to be working either. I think the problem is that when I call the copy-assignment operator (<code>*this = Tree(&amp;aTemp, &amp;bTemp, depth, depth)</code>), the copy constructor should be called (since the argument of the copy-assignement operator is passed by value), but it seems that this is not happening. I do not understand why.</p>
  
  <p>Thanks in advance for helping!</p>