title: in C++ which happens first, the copy of a return object or local object's destructors?
body: <p>I imagine there's an answer to this somewhere, but I couldn't find it because there are lots of threading questions, and mine's pretty simple by comparison.</p>
  
  <p>I'm not trying to make a threadsafe copy or assignment constructor or anything like that.</p>
  
  <p>What I'm wondering, is if I have a class that represents a mutex lock and I return from a function that instantiates it, which happens first, the destructor of my mutex (thus unlocking it) or the copy constructor of the return value. Here's my example:</p>
  
  <pre><code>string blah::get_data(void)
    {
      MutexLock ml(shared_somewhere_else); // so this locks two threads from calling get_data at the same time
  
      string x = "return data";
      return x;
    }
  </code></pre>
  
  <p>Somewhere else, we call get_data...</p>
  
  <pre><code> string result = get_data();
  </code></pre>
  
  <p>Thinking back to C for a second, you never return a pointer to a global variable, because the local variable goes out of scope after you return.</p>
  
  <p>C++ doesn't have this problem because x will get copied into result. What I'm wondering is when that happens. Will my lock free before the copy is made? </p>
  
  <p>In this simple example "return data" is static information, but what I'm working with, it's data that can be changed by another thread (also locked on the same MutexLock) so if the lock frees before the copy-to-result is made, the copy could get corrupted.</p>
  
  <p>I'm not sure I'm explaining the question well, so I'll try to clarify if this doesn't make sense.</p>