title: Read write mutex on a const reference getter (using Qt)
body: <p>I employ the following scheme in my Model-View-Controller program:</p>
  
  <pre><code>class model{
  
  public
  const submodelA&amp; getSubModA() const;
  const submodelB&amp; getSubModB() const;
  
  private:
  submodelA _submod_a;
  submodelA _submod_b;
  
  }
  </code></pre>
  
  <p>One thread will write to the submodels using signal-slot connections. Many threads will read from these submodels.</p>
  
  <p>I would therefore like to employ a read-write lock. However, I want to avoid the following:</p>
  
  <pre><code>...
  _model.getSubModA().getQReadWriteLock().lockForRead();
  int foo = _model.getSubModA().getFoo();
  _model.getSubModA().getQReadWriteLock().unlock();
  ...
  </code></pre>
  
  <p>As you can see, this is unnecessarily verbose.</p>
  
  <p>I would like to do just </p>
  
  <pre><code>int foo = _model.getSubModA().getFoo();
  </code></pre>
  
  <p>The getters of the submodels should return const references, such as to avoid unnecessary copies.</p>
  
  <p>Is it possible to encapsulate this functionality in the getter somehow?</p>
  
  <pre><code>const model::submodelA&amp; getSubModA() const{
  
  _submod_a.getQReadWriteLock().lockForRead();
  return _submod_a;
  
  }
  </code></pre>
  
  <p>Obviously, the problem here is that I can't unlock after the return. I was thinking of hacking around this by including a local variable with a reference to the readwrite lock, which would unlock it in its destructor, but I'm worried it could somehow lead to undefined behavior, since it is being returned by reference.</p>
  
  <p>Are there any patterns or practices that solve this problem?</p>