title: How to avoid copying when emitting object from separate thread using Qt/C++?
body: <p>My goal: pass an object generated by a child thread to the main program thread, where it is read, copying it as few times as possible.</p>
  
  <p><strong>What Works</strong></p>
  
  <p>An object owned by the child thread, with this field as intermediate store:</p>
  
  <pre><code>private:
     cv::Mat rgb;
  </code></pre>
  
  <p>A simple getter method for that field:</p>
  
  <pre><code>cv::Mat freenect2_pipe::take_rgb(){
      return this-&gt;rgb;
  }
  </code></pre>
  
  <p>Using both of the above when emitting the object to the main thread:</p>
  
  <pre><code>    std::vector&lt;cv::Mat&gt; images;
      while (!stop_requested &amp;&amp; !pause_requested
              &amp;&amp; rgbd_camera.Capture(images)
              ) {
          rgb = images[0];
          emit rgb_frame(take_rgb());
      }
  </code></pre>
  
  <p>Signal definition:</p>
  
  <pre><code>    void rgb_frame(const cv::Mat&amp; image);
  </code></pre>
  
  <p><strong>What Does Not Work</strong></p>
  
  <p>-emitting (a)  <code>rgb_frame(images[0])</code>, (b) <code>rgb_frame(rgb)</code>, or (c) rgb_frame(locally_created_copy_of_frame).</p>
  
  <p><strong>Where/How Does it Fail?</strong></p>
  
  <p>Segfaults when trying to read from the generated object (in this case, an OpenCV matrix).</p>
  
  <p>*How do I achieve the goal?*s</p>
  
  <p><strong>Additional Information</strong></p>
  
  <p>1) The <code>images</code> array above is generated in a third, non-qt thread which is launched by the child thread. This happens in third-party code I cannot modify.</p>
  
  <p>2) The segfault behavior is consistent whether I use QThreads or C++11 threads (probably, both use pthread in the background on my platform). When using C++11 threads directly, I create my own intermediate shared buffer. Hence (void) is emitted, but the main thread pops the object from the shared buffer on que. However, the read fails exactly at the same place.</p>
  
  <p>[Edit]
  Slot definition: <code>void tmp_display_rgb2(const cv::Mat&amp; rgb);</code></p>