Disadvantages of shared_ptr

c++, c++11, shared-ptr, smart-pointers

Solution

Of course there are disadvantages: you require extra memory to maintain a reference count, and every time you copy or destroy a `shared_ptr` instance this reference count has to be incremented and decremented. If your program uses multiple threads then the manipulation of the reference count has to be done in a thread-safe manner, which can add some additional overhead, the magnitude of which depends on the implementation.

Whether or not this overhead impacts your program in an overall negative way depends on the details of your program. Generally you should only use `std::shared_ptr` for resources that truly need to be shared, because it can be somewhat arbitrary which object will need them last. In other cases, a single point of ownership is usually easier to maintain because you know exactly how long each resource will be alive.

Additionally, you need to be aware that `std::shared_ptr` is not a panacea for object lifetime management. In particular, if you have two objects that each own an `std::shared_ptr` to the other, the objects have cyclic ownership and will never be automatically deleted unless you first break the cycle by invoking `reset()` on one of them.

Problem

With shared_ptr included in c++11, one could achieve a semi garbage-collected enviroment. Does the (inflationary?) usage come along with some disadvantages? I could imagine a class model, where you create a class in which you typedef your class at the end as a shared_ptr to abbreviate the syntax. ``` ///////////////// //// MyClass //// ///////////////// #include <memory> class MyClass { public: Myclass(); }; typedef std::shared_ptr<MyClass> SharedMyClass; /////////////////////// //// Example Class //// /////////////////////// class Example { public: Example(): myClassObject(new MyClass()) {} private: SharedMyClass myClassObject; }; ```

Original source

Related problems