5

I have a question because it is not clear to me when function arguments get destroyed. Therefore, is the concatenation of the following doSomething function error-prone or not?

I’m asking because "it is the programmer's responsibility to ensure that std::string_view does not outlive the pointed-to character array". Can that be guaranteed in that specific case or not?

#include <string>
#include <string_view>

std::string doSomething(const std::string_view& str_view)
{
    // do something and create a new std::string instance based on the std::string_view instance

    return str;
}

int main()
{
    std::string input_str{"Hello world!"};

    std::string output_str{ doSomething(doSomething(doSomething(input_str))) };

    return 0;
}
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
  • 2
    well, you return `std::string`, it doesn't depend on the `std::string_view` anyway. – apple apple May 13 '21 at 14:45
  • The pointed-to character array in this case is `input_str.data()`, which lives until `main` returns, which is definitely longer than any of the `str_view` arguments last. – Nathan Pierson May 13 '21 at 14:48
  • related/dupe: https://stackoverflow.com/questions/27195825/function-parameters-are-not-destroyed-at-that-functions-exit – NathanOliver May 13 '21 at 14:50
  • 1
    @NathanOliver That question seems to address function parameters and not function arguments. –  May 13 '21 at 15:26

1 Answers1

3

The anonymous temporary passed to the (const reference) parameter const std::string_view& str_view survives the function call.

Since there are nested functions, the anonymous temporaries are not destroyed until, conceptually, the closing semicolon of

std::string output_str{ doSomething(doSomething(doSomething(input_str))) };
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Did I understand you correctly, all the std::string's used as function arguments won't only exist as temporary objects at the beginning of the function call (to construct the std::string_view's)? Which means, that they will at least exist until the function body was executed completely? –  May 13 '21 at 15:34
  • 4
    @D3V0N5H1R3: Exactly. No `std::string`s are destroyed until you get to `;`. And they are destroyed in the reverse order of construction. – Bathsheba May 13 '21 at 15:46
  • As an aside, is there any benefit to putting const& on a string_view? My impression was "no". – wrhall May 13 '21 at 20:56