title: Initialization list and move constructors
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/8193102/initializer-list-and-move-semantics">initializer_list and move semantics</a>  </p>
  </blockquote>
  
  
  
  <p>In the following example, a copy is finally performed even if a temporary object is sended:</p>
  
  <pre><code>// test.cpp
  
  #include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;utility&gt;
  #include &lt;initializer_list&gt;
  
  using namespace std;
  
  class mystr : public string
  {
  public:
      mystr() = default;
      mystr(const char* c) : string(c) { }
  
      mystr(mystr&amp; m) : string(m) { cout &lt;&lt; "&amp; " &lt;&lt; c_str() &lt;&lt; endl; }
      mystr(mystr const &amp; m) : string(m) { cout &lt;&lt; "const &amp; " &lt;&lt; c_str() &lt;&lt; endl; }
      mystr(mystr&amp;&amp; m) : string(move(m)) { cout &lt;&lt; "&amp;&amp; " &lt;&lt; c_str() &lt;&lt; endl; }
  };
  
  class myvector
  {
  public:
      myvector(initializer_list&lt;mystr&gt; i)
      {
          cout &lt;&lt; "Inside constructor" &lt;&lt; endl;
  
          v = vector&lt;mystr&gt;(i);
      }
  
  private:
      vector&lt;mystr&gt; v;
  };
  
  int main()
  {
      mystr a("hello");
  
      myvector v{ a, mystr("bye"), a, mystr("sorry") };
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>$ g++ --version | grep "g++"
  g++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2
  $ g++ -std=c++11 test.cpp
  $ ./a.out
  &amp; hello
  &amp; hello
  Inside constructor
  const &amp; hello
  const &amp; bye
  const &amp; hello
  const &amp; sorry
  </code></pre>
  
  <p>The "named" objects are copied and the temporary objects are elided, but, once the initializator list is constructed, all elements are copied other time: the initializator list has erased information of the original nature of the object. With <code>-fno-elide-constructors</code> the process is better understandable:</p>
  
  <pre><code>$ g++ -std=c++11 -fno-elide-constructors test.cpp
  $ ./a.out
  &amp; hello
  &amp;&amp; hello
  &amp;&amp; bye
  &amp;&amp; bye
  &amp; hello
  &amp;&amp; hello
  &amp;&amp; sorry
  &amp;&amp; sorry
  Inside constructor
  const &amp; hello
  const &amp; bye
  const &amp; hello
  const &amp; sorry
  </code></pre>
  
  <p>The temporaries are moved two times, and the persistent objects are copied and moved, before arriving to the constructor, that means, in the process to create the initializator list. Once in the constructor, all objects in the list are persistents from the point of view of the constructor, and thus, they are all copied.</p>
  
  <p>Is it possible to avoid this behaviour (forwarding)?</p>
  
  <p>I think, a container should always move the objects (and not copy) from the initializator list to its own container, since the object are already copied one time when the initializer list is built. Why to copy two consecutive times?</p>