title: Is it possible to implement a DefaultIfNull function in C++?
body: <p>Disclaimer: This is rather more out of curiosity than for a lack of other solutions!</p>
  <p><strong>Is it possible to implement a function in C++ that</strong>:</p>
  <ul>
  <li>gets passed a pointer of type T</li>
  <li>either returns a reference-like-thing to the object pointed to by T</li>
  <li>or, if the pointer is null, returns a reference-like-thing to a default constructed <code>T()</code> <em>that has some sane lifetime</em>?</li>
  </ul>
  <p>Our first try was:</p>
  <pre><code>template&lt;typename T&gt;
  T&amp; DefaultIfNullDangling(T* ptr) {
      if (!ptr) {
          return T(); // xxx warning C4172: returning address of local variable or temporary
      } else {
          return *ptr;
      }
  }
  </code></pre>
  <p>A second attempt was done like this:</p>
  <pre><code>template&lt;typename T&gt;
  T&amp; DefaultIfNull(T* ptr, T&amp;&amp; callSiteTemp = T()) {
      if (!ptr) {
          return callSiteTemp;
      } else {
          return *ptr;
      }
  }
  </code></pre>
  <p>This gets rid of the warning and <a href="https://stackoverflow.com/a/12554621/321013">somewhat extends the lifetime</a> of the temporary, but it's still rather error prone, I think.</p>
  <hr />
  <p>Background:</p>
  <p>The whole thing was triggered by an access pattern that looked like this:</p>
  <pre><code>if (pThing) {
    for (auto&amp; subThing : pThing-&gt;subs1) {
      // ...
      if (subThing.pSubSub) {
        for (auto&amp; subSubThing : *(subThing.pSubSub)) {
           // ...
        }
      }
    }
  }
  </code></pre>
  <p>that could be &quot;simplified&quot; to:</p>
  <pre><code>for (auto&amp; subThing : DefaultIfNull(pThing).subs1) {
      // ...
      for (auto&amp; subSubThing : DefaultIfNull(subThing.pSubSub)) {
          // ...
      }
  }
  </code></pre>