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 imag
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.
One other thing worth mentioning is that you need to be very careful when designing your APIs with std::shared_ptr
.
The obvious advantage over a raw pointer is the automatic memory management (with the cyclic ownership gotcha) but other problems/questions remain. When the resource is shared, you're giving up (to some extent) control and the ability to reason about your code.
Can I modify the object given that I might not be the only one holding onto it?
You change the object and the change reflects to the whole system. The larger the system, the less obvious are the implications and it's harder to prove that it's in fact safe to do. Sean Parent often says that a shared ptr is in fact as good as a global variable.
I performance is important I wold not use std::sahred_ptr. For example, to sort an array may with real pointers is 5 times faster than to sort with shared pointers.
On the other hand shared pointer do not avoid all troubles with garbage leaks in case of circular references. Of course, this can be solved with weak_ptr, but what I mean is, that shared pointer need also be handled carfully.
I prefer to use shared_ptr for static elements, because static elements are not deleted by a destructor of a class.