title: std::thread initialization with class argument results with class object being copied multiple times
body: <p>It seems that if you create an object of a class, and pass it to the std::thread initialization constructor, then the class object is constructed and destroyed as much as 4 times overall. My question is: could you explain, step by step, the output of this program? Why is the class being constructed, copy-constructed and destructed so many times in the process?</p>
  
  <p>sample program:  </p>
  
  <pre><code>#include &lt;iostream&gt;  
  #include &lt;cstdlib&gt;
  #include &lt;ctime&gt;
  #include &lt;thread&gt;
  
  class sampleClass {
  public:
      int x = rand() % 100;
      sampleClass() {std::cout &lt;&lt; "constructor called, x=" &lt;&lt; x &lt;&lt;     std::endl;}
      sampleClass(const sampleClass &amp;SC) {std::cout &lt;&lt; "copy constructor called, x=" &lt;&lt; x &lt;&lt; std::endl;}
      ~sampleClass() {std::cout &lt;&lt; "destructor called, x=" &lt;&lt; x &lt;&lt; std::endl;}
      void add_to_x() {x += rand() % 3;}
  };
  
  void sampleThread(sampleClass SC) {
      for (int i = 0; i &lt; 1e8; ++i) { //give the thread something to do
          SC.add_to_x();
      }
      std::cout &lt;&lt; "thread finished, x=" &lt;&lt; SC.x &lt;&lt; std::endl;
  }
  
  int main(int argc, char *argv[]) {
      srand (time(NULL));
      sampleClass SC;
      std::thread t1 (sampleThread, SC);
      std::cout &lt;&lt; "thread spawned" &lt;&lt; std::endl;
      t1.join();
      std::cout &lt;&lt; "thread joined" &lt;&lt; std::endl;
      return 0;
  }
  </code></pre>
  
  <p>The output is:</p>
  
  <pre><code>constructor called, x=92
  copy constructor called, x=36
  copy constructor called, x=61
  destructor called, x=36
  thread spawned
  copy constructor called, x=62
  thread finished, x=100009889
  destructor called, x=100009889
  destructor called, x=61
  thread joined
  destructor called, x=92
  </code></pre>
  
  <p>compiled with gcc 4.9.2, no optimization.</p>