Search code examples
c++argumentsc++17destructorstring-view

When exactly are function arguments being destructed?


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;
}

Solution

  • 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))) };