title: When to return a pointer, scalar and reference in C++?
body: <p>I'm moving from Java to C++ and am a bit confused of the language's flexibility. One point is that there are three ways to store objects: A pointer, a reference and a scalar (storing the object itself if I understand it correctly).</p>
  
  <p>I tend to use references where possible, because that is as close to Java as possible. In some cases, e.g. getters for derived attributes, this is not possible:</p>
  
  <pre><code>MyType &amp;MyClass::getSomeAttribute() {
      MyType t;
      return t;
  }
  </code></pre>
  
  <p>This does not compile, because <code>t</code> exists only within the scope of <code>getSomeAttribute()</code> and if I return a reference to it, it would point nowhere before the client can use it.</p>
  
  <p>Therefore I'm left with two options:</p>
  
  <ol>
  <li>Return a pointer</li>
  <li>Return a scalar</li>
  </ol>
  
  <p>Returning a pointer would look like this:</p>
  
  <pre><code>MyType *MyClass::getSomeAttribute() {
      MyType *t = new MyType;
      return t;
  }
  </code></pre>
  
  <p>This'd work, but the client would have to check this pointer for <code>NULL</code> in order to be really sure, something that's not necessary with references. Another problem is that the caller would have to make sure that <code>t</code> is deallocated, I'd rather not deal with that if I can avoid it.</p>
  
  <p>The alternative would be to return the object itself (scalar):</p>
  
  <pre><code>MyType MyClass::getSomeAttribute() {
      MyType t;
      return t;
  }
  </code></pre>
  
  <p>That's pretty straightforward and just what I want in this case: It feels like a reference and it can't be null. If the object is out of scope in the client's code, it is deleted. Pretty handy. However, I rarely see anyone doing that, is there a reason for that? Is there some kind of performance problem if I return a scalar instead of a pointer or reference?</p>
  
  <p>What is the most common/elegant approach to handle this problem?</p>