3 ms·
It shouldn't be. std::unique_ptr is very clear. (std::shared_ptr should be used only when absolutely required and should be kept under close watch the whole ti
by eropple 6y ago
It shouldn't be. std::unique_ptr is very clear.
(std::shared_ptr should be used only when absolutely required and should be kept under close watch the whole time.)
- djmips 6y agosearches codebase I'm working on... finds thousands and thousands of std::shared_ptr (many involve a typedef, so there are even more...) eep! Should I be alarmed?
- hedora 6y agoYes. On reflection, or on ramping up new developers, I think you’ll find that it is unnecessarily difficult to reason about object lifetimes. There’s a good chance that most of the shared_ptr’s can be replaced by unique_ptr, which has less runtime overhead. More importantly, it documents the intent of the programmer regarding ownership semantics, and the timespan during which the object should be remain valid.
- cesarb 6y agoIf that codebase is older than C++0x, many of these std::shared_ptr could be taking the place of std::unique_ptr (which didn't exist back then; std::auto_ptr was a footgun). If you're in the mood for a refactoring, you could take a look at each one and see whether then can be replaced by std::unique_ptr, or whether they really have shared ownership semantics (which is what std::shared_ptr should be used for).
- usefulcat 6y agoNeither std::unique_ptr nor std::shared_ptr existed prior to c++11. Perhaps you're thinking of boost::shared_ptr or boost::scoped_ptr, both of which have existed in one form or another for somewhere around 20 years.
- Arnavion 6y agoNot necessarily. The concern about when the shared_ptr'd value runs its destructor only matters if the value's destructor is something you care about. If you have a situation where a value needs to be shared between multiple other values, but also the value is trivial enough that it doesn't matter when it's destroyed or what it does when it's destroyed, but also the value is not so trivial that you can copy it instead of using a refcounting pointer, then std::shared_ptr is fine.
- eropple 6y ago"Fine" is probably pushing it, but "not the biggest problem you are likely to have" is probably true. But, like, it's easy to accidentally get yourself into situations where somebody forgot to use std::weak_ptr somewhere and you start leaking memory. Unless you know you must share objects with multiple potential owners, though, std::unique_ptr is a lot wiser.
- Arnavion 6y agoYes, when I wrote: >but also the value is trivial enough that it doesn't matter when it's destroyed or what it does when it's destroyed" that precludes the value from having other refcounting pointers that could then create cycles and leak.