Why don't const l-value references to r-values result in dangling references?

Why is the following not an error?

const auto& foo = std::string("foo");

In my mental model of C++ I think of references as glorified non-null pointers that the language wraps in syntactic sugar for me. However the code below would be an error but the above is not.

const auto* foo = &(std::string("foo"));

In the reference case why is the string not immediately destructed after the r-value expression is evaluated?

>Solution :

Because this is the language rule Lifetime of a temporary

Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference.

There is no such rule for const pointers.

Leave a Reply