Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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

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

So my question is, should I just use shared_ptr<myType> when I new the instance and then pass normal pointers around or should I be passing shared_ptr<myType> everywhere?

like image 480
CodingHero Avatar asked Feb 05 '12 19:02

CodingHero


1 Answers

Creating a shared_ptr doesn't imbue magical powers on its pointee object. The magic is all in the shared_ptr — and its copies — itself. If you stop using it, you lose your reference counting; worse, because you used it at some point, the object will be automatically deleted when you don't expect it.

The whole point of having shared_ptr is that you know your object won't get destroyed when you're still using it somewhere.

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 extract a raw pointer, but these should be rare. If you are in a function where you know you don't need the reference counting, then just pass the shared_ptr in by reference.

like image 66
Lightness Races in Orbit Avatar answered Sep 28 '22 22:09

Lightness Races in Orbit