title: Returning pointers in a thread-safe way
body: <p>Assume I have a thread-safe collection of Things (call it a ThingList), and I want to add the following function.</p>
  
  <pre><code>Thing * ThingList::findByName(string name)
  {
    return &amp;item[name]; // or something similar..
  }
  </code></pre>
  
  <p>But by doing this, I've delegated the responsibility for thread safety to the calling code, which would have to do something like this:</p>
  
  <pre><code>try 
  {
    list.lock(); // NEEDED FOR THREAD SAFETY
    Thing *foo = list.findByName("wibble");
    foo-&gt;Bar = 123;
    list.unlock();  
  }
  catch (...) 
  {
    list.unlock();
    throw;
  } 
  </code></pre>
  
  <p>Obviously a RAII lock/unlock object would simplify/remove the try/catch/unlocks, but it's still easy for the caller to forget.</p>
  
  <p>There are a few alternatives I've looked at:</p>
  
  <ul>
  <li>Return Thing by value, instead of a
  pointer - fine unless you need to
  modify the Thing</li>
  <li>Add function <code>ThingList::setItemBar(string name, int value)</code> - fine, but these tend to
  proliferate</li>
  <li>Return a pointerlike object which locks the list on creation and unlocks it again on destruction. Not sure if this is good/bad practice...</li>
  </ul>
  
  <p>What's the right approach to dealing with this?</p>