c++ – shared_ptr vs scoped_ptr

c++ – shared_ptr vs scoped_ptr

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 youve finished with a single reference, use scoped_ptr.

Performanceshared_ptr has more functionality, but also requires an additional allocation (its also larger, but that rarely matters).

[edit] The second allocation can be avoided by using make_shared, but then weak_ptr will hold the entire entire allocation even after the object is destroyed, which may be a problem for large objects.

Expresison of Intent using scoped_ptr you state more explicitly what you want to do. (In case you wonder – thats a good thing 🙂 ). If you do this correctly, shared_ptr will also indicate this object is intended to live beyond this scope

c++ – shared_ptr vs scoped_ptr

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 whats the point? shared_ptr has likely a slightly bigger overhead with all the reference counting involved.

Leave a Reply

Your email address will not be published.