When using shared_ptr, should I just use the shared_ptr declaration once or declare shared_ptr everywhere, where do I pass it?

When using shared_ptr should I just use the shared_ptr declaration once or declare shared_ptr everywhere when I pass it?

So, in a function where I am new to the instance, I wrap it in shared_ptr , but when I return it from the function, I can also return shared_ptr or, using get() in shared_ptr , just return the normal pointer.

So my question is: should I just use shared_ptr<myType> when I update the instance and then pass the usual pointers, or should I go through shared_ptr<myType> everywhere?

+7
source share
1 answer

Creating shared_ptr does not inherit magic powers on a pointee object. Magic is all in shared_ptr - and its copies; myself. If you stop using it, you will lose the reference count; worse because you used it at some point, the object will be automatically deleted if you do not expect it.

The whole point of having shared_ptr is that you know that your object will not be destroyed when you are still using it.

In the following:

 T* foo() { shared_ptr<T> sp(new T()); return sp.get(); // ^ the only shared_ptr<T> referencing the obj is dead; // obj is deleted; // returned pointer invalid before you can even do anything with it } 

your pointer is immediately invalid.

There may well be circumstances in which you retrieve a raw pointer, but they should be rare. If you are in a function in which you know that you do not need reference counting, just pass shared_ptr by reference.

+5
source

All Articles