c++c++17stdstringstring-view

Is it safe to pass an `std::string` temporary into an `std::string_view` parameter?


Suppose I have the following code:

void some_function(std::string_view view) {
    std::cout << view << '\n';
}

int main() {
    some_function(std::string{"hello, world"}); // ???
}

Will view inside some_function be referring to a string which has been destroyed? I'm confused because, considering this code:

std::string_view view(std::string{"hello, world"});

Produces the warning (from clang++):

warning: object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]

What's the difference?

(Strangely enough, using braces {} rather than brackets () to initialise the string_view above eliminates the warning. I've no idea why that is either.)

To be clear, I understand the above warning (the string_view outlives the string, so it holds a dangling pointer). What I'm asking is why passing a string into some_function doesn't produce the same warning.


Solution

  • some_function(std::string{"hello, world"}); is completely safe, as long as the function doesn't preserve the string_view for later use.

    The temporary std::string is destroyed at the end of this full-expression (roughly speaking, at this ;), so it's destroyed after the function returns.


    std::string_view view(std::string{"hello, world"}); always produces a dangling string_view, regardless of whether you use () or {}. If the choice of brackets affects compiler warnings, it's a compiler defect.