Search code examples
c++shared-ptrrvalue

Dereference a rvalue shared_ptr


I'm using a library which export a function like:

// there is some type T
std::shared_ptr<T> foo(params);

and while the following code works fine:

auto p = foo(params);
auto & v0 = *p;
// use v0 as a T's reference

the below crashes:

auto & v1 = *foo(params);
// use v1 as a T's reference

So what is the difference between v0 and v1? Many thanks for any help.


Solution

  • 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.