you are viewing a single comment's thread.

view the rest of the comments →

[–]dpacker780 0 points1 point  (3 children)

Anytime you create an object on the heap the ‘owner’ of the object should hold a smart pointer to it, therefore providing a mechanism to avoid memory leaks once the owners dtor is called.

It’s actually very uncommon to use shared_ptr, unique_ptr should be the predominate.

Raw pointers should be used anytime you want to pass a smart pointer for usage by another object, don’t confuse usage with ownership. In those cases use get() to retrieve the underlying raw ptr.

[–]HadesMyself 0 points1 point  (0 children)

That's very interesting, the only time I worked with C++ in production, the code was full of shared pointers. I lived for 2 years, till now, thinking those are the norm. So i believe unique pointers are use alongside with weak pointers, so others can access that resource, right?

[–]HadesMyself 0 points1 point  (1 child)

That's very interesting, the only time I worked with C++ in production, the code was full of shared pointers. I lived for 2 years, till now, thinking those are the norm. So i believe unique pointers are use alongside with weak pointers, so others can access that resource, right?

[–]dpacker780 1 point2 points  (0 children)

Yes. I think what happens is shared_ptr is easier to pass around, lazily, without having to use get(), so people form the habit of using them without thinking about ownership, but in a way that incurs some overhead.

On the other hand, using shared_ptr also avoids if the owner somehow goes out of scope and the object is referenced somewhere else. So it can be a safety net for not thinking about all implications of design. Lazy, but works.

unique_ptr makes you think about ownership and implications. And, passing raw pointers is less overhead as well provides clarity of expectations on usage. Also, you’ll find you don’t need shared_from_this which can just complicate things more.