Skip to content

Comment on Modern C++ – RAIIparent

Comments

With shared_ptr you completely lose track who actually owns an object or when it will get destructed. It encourages sloppy programming and makes code much harder to read and reason about.

Unlike most languages that have ref-counting build in, shared_ptr also doesn't provide anything to deal with cyclic dependencies, so you can end up with memory leaks.

The most important reason however is simply that you don't need it like 99% of the time, unique_ptr provides enough functionality to work just fine as a shared_ptr replacement in most situations. And in the rare cases where you really need a shared_ptr, you can just convert a unique_ptr into one.

Author here, parent comment describes it very well — shared_ptr are a last resort, not a first one.

They are quite heavily (and badly) used in some code bases (ROS). I'm planning a future article that covers shared_ptr in more details.

The surprising thing about shared pointer is that a `const shared_ptr<T>` means that you can modify the contents of T. This makes the problem, mentioned in the parent, of keeping track of who can modify the object where impossible. I've never encountered a `const shared_ptr<const T>` but that would be a better approach.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.