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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With