Why does std::string_view create a dangling view in a ternary expression? : <p>Consider a method that returns a <code>std::string_view</code> either from a method that returns a <code>const std::string&amp;</code> or from an empty string. To my surprise, writing the method this way results in a dangling string view:</p>

<pre><code>const std::string&amp; otherMethod();

std::string_view myMethod(bool bla) {
    return bla ? otherMethod() : ""; // Dangling view!
}
</code></pre>

<p><a href="https://godbolt.org/z/1Hu_p2" rel="noreferrer">https://godbolt.org/z/1Hu_p2</a></p>

<p>It seems that the compiler first puts a temporary <code>std::string</code> copy of the result of <code>otherMethod()</code> on the stack and then returns a view of this temporary copy instead of just returning a view of the reference. First I thought about a comipler bug, but both G++ and clang do this.</p>

<p>The fix is easy: Wrapping <code>otherMethod</code> into an explicit construction of <code>string_view</code> solves the issue:</p>

<pre><code>std::string_view myMethod(bool bla) {
    return bla ? std::string_view(otherMethod()) : ""; // Works as intended!
}
</code></pre>

<p><a href="https://godbolt.org/z/Q-sEkr" rel="noreferrer">https://godbolt.org/z/Q-sEkr</a></p>

<p>Why is this the case? Why does the original code create an implicit copy without warning?</p>
