views:

687

answers:

4

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!

+1  A: 

scoped_ptr works much faster from shared_ptr. It's right. shared_ptr always allocate memory using your allocator or default allocator.

Alexey Malistov
+3  A: 

Their intended purpose is different, so, in many cases "shared_ptr vs scoped_ptr" is not a question at all. Sure, you can use a shared_ptr when all you need is a scoped_ptr. But what's the point? shared_ptr has likely a slightly bigger overhead with all the reference counting involved.

sellibitze
+11  A: 

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.

Mike Seymour
Mike, I couldn't agree more. I always advise people to start with `boost::scoped_ptr`. If you need transfer of ownership semantics (maintaining single ownership) then "upgrade" to `std::auto_ptr`. If you need shared ownership only then do you use `boost::shared_ptr`.Also, the `Boost.ptr_container` library is a nice alternative to containers of boost::shared_ptr when the elements don't really need to be shared.
David Joyner
As an aside: if you do need shared pointers, you can get rid of the extra allocations by allocating objects using `make_shared` or `allocate_shared` instead of `new`.
Mike Seymour
@David: I mostly agreed, but I'd skip `auto_ptr` entirely. It can't be used safely in standard containers, so it's likely to spring a few nasty surprises if you're not *really* careful.
jalf
+5  A: 

Performance - shared_ptr has more functionality, but also requires an additional allocation (it's also larger, but that rarely matters).

Expresison of Intent using scoped_ptr you state more explicitly what you want to do. (In case you wonder - that's a good thing :) ). If you do this correctly, shared_ptr will also indictae "this object is intended to live beyond this scope"

peterchen
+1 for expression of intent. In that vein, `scoped_ptr` is very clear as is `shared_ptr`. Likewise, use of `std::auto_ptr` should signal that you're willing to transfer ownership of the object at some point.
David Joyner