Consider a method that returns a std::string_view either from a method that returns a const std::string& or from an empty string. To my surprise, writing the method this way results in a dangling string view:
const std::string& otherMethod();
std::string_view myMethod(bool bla) {
return bla ? otherMethod() : ""; // Dangling view!
}
It seems that the compiler first puts a temporary std::string copy of the result of otherMethod() 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.
The fix is easy: Wrapping otherMethod into an explicit construction of string_view solves the issue:
std::string_view myMethod(bool bla) {
return bla ? std::string_view(otherMethod()) : ""; // Works as intended!
}
Why is this the case? Why does the original code create an implicit copy without warning?