Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 238
Ta Thanh Dinh Avatar asked Jun 26 '19 09:06

Ta Thanh Dinh


People also ask

What does shared_ptr get () do?

A shared_ptr may share ownership of an object while storing a pointer to another object. get() returns the stored pointer, not the managed pointer.

Should I use Unique_ptr or shared_ptr?

Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.

Do I need to delete a shared_ptr?

So no, you shouldn't. The purpose of shared_ptr is to manage an object that no one "person" has the right or responsibility to delete, because there could be others sharing ownership. So you shouldn't ever want to, either.

What is the difference between shared_ptr and Weak_ptr?

The only difference between weak_ptr and shared_ptr is that the weak_ptr allows the reference counter object to be kept after the actual object was freed. As a result, if you keep a lot of shared_ptr in a std::set the actual objects will occupy a lot of memory if they are big enough.


Video Answer


1 Answers

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.

like image 138
StoryTeller - Unslander Monica Avatar answered Oct 03 '22 01:10

StoryTeller - Unslander Monica