Smart Pointers in C++: std::unique_ptr, std::shared_ptr, std::weak_ptr

Hi folks, I was building a personal project this weekend and ended up using a lot of smart pointers in C++. Ive noticed that many people find them confusing at first, so here’s a simple way I think about them: 1. std::unique_ptr Use this when there is clear, single ownership. The object’s lifetime is tied to one owner, and ownership can be transferred using std::move. 2. std::shared_ptr Use this when multiple parts of your system need to share ownership of an object. The object lives until the last reference is released, preventing premature deletion. Be careful though cyclic references can lead to memory leaks. 3. std::weak_ptr A non-owning reference to an object managed by shared_ptr. It does not affect the object’s lifetime and is mainly used to break cyclic dependencies. Still exploring more real-world patterns around this. Would love to hear how others approach this. #cpp #multithreading #systemsprogramming

It’s good to people using smart pointers. However, we need to enforce that using raw pointers is almost never a nice idea, until we are working on low level data structures. And as Sean says, smart pointers are also raw pointers.

To view or add a comment, sign in

Explore content categories