If I capture a return value in an auto&, will that be destroyed from under me?

Viewed 44

Take the following code:

const std::string GetString()
{
    return std::string();
}

auto& thisIsANewString = GetString();

What happens in this scenario? It compiles successfully, but does the auto reference keep the string around? Or does it get destroyed and I'm left with an orphaned reference?

The reason I'm giving this a go is to maintain the const on the return value, whereas just doing a straight auto usage takes a copy.

1 Answers

What happens in this scenario?

The reference is bound to a temporary object, and the lifetime of the temporary object is extended to match the lifetime of the reference.

This is useful in templates where you will be able to treat references, and objects that are reference wrappers equally. It's only confusing to use temporary lifetime extension outside of templates, but it is allowed.

whereas just doing a straight auto usage takes a copy.

Just to clarify, there are zero copies in this program:

std::string GetString()
{
    return {};
}

auto thisIsANewString = GetString();

... at least since C++17. Prior to that, there is technically a move that compilers are allowed, but not required to optimise away. Prior to C++11 there is technically a copy that compilers are allowed, but not required to optimise away.

Related