Dereference a rvalue shared_ptr

The object pointed at by a shared_ptr exists only as long as there is at least one shared pointer alive that still points at it.

In your example there is likely only one such pointer, and it's returned by foo.

For v0, p becomes the shared_ptr keeping the object alive.

For v1, there is only a temporary shared pointer that exists only for the duration of v1's initialization. The pointer and object being pointed at are gone by the time you use the reference, making it a dangling one at the point of use.


The statement

auto & v1 = *foo(params);

is a potential undefined behavior.

The function foo probably construct a std::shared_ptr inside and returns it to the caller as a temporary object (technically a prvalue) which is supposed to be assigned to some variable.

You don't assign the smart pointer of your expression to any variable. However, you grab the object pointed by (using the * operator) and assign it to the reference v1.

At the end of the expression evaluation the temporary std::shared_ptr will be destroyed and (being a smart pointer) the object pointed as well.

Therefore, auto & v1 is referring to a destroyed object and accessing to it is an undefined behavior (producing a segmentation fault in the majority of cases).