scoped_ptr
is not copy able and is being deleted out of the scope. So it is kind of restricted shared_ptr
. So seems besides the cases when you really need to restrict the copy operation shared_ptr
is better to use. Because sometimes you don’t know you need to create a copy of your object or no. So the question is: besides the cases mentioned above, could we consider that shared_ptr
is better (or recommended) to use instead of scoped_ptr
. Does scoped_ptr
work much faster from shared_ptr
, or does it have any advantages?
Thanks!
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.
In short: 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, we should use shared_ptr when we want to assign one raw pointer to multiple owners. // referring to the same managed object. When to use shared_ptr? Use shared_ptr if you want to share ownership of a resource.
shared_ptr are noticeably slower than raw pointers. That's why they should only be used if you actually need shared ownership semantics. Otherwise, there are several other smart pointer types available. scoped_ptr and auto_ptr (C++03) or unique_ptr (C++0x) both have their uses.
shared_ptr
is more heavyweight than scoped_ptr
. It needs to allocate and free a reference count object as well as the managed object, and to handle thread-safe reference counting - on one platform I worked on, this was a significant overhead.
My advice (in general) is to use the simplest object that meets your needs. If you need reference-counted sharing, use shared_ptr
; if you just need automatic deletion once you've finished with a single reference, use scoped_ptr
.
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