logoalt Hacker News

HarHarVeryFunnytoday at 3:27 AM0 repliesview on HN

It's really asking for trouble if you view it that way - that you are going to allocate something, then uniquely pass it to a single unique_ptr, or shared_ptr, to manage and release. Better really to use std::make_unique() and std::make_shared().

The smartness, limited though it may be, is just that since it "knows" it's the owner, it knows that it's responsible for releasing it at the appropriate time (reference counted in the case of a shared pointer).

A lot of the value isn't just the automatic release, but that these classes, unique_ptr, and shared_ptr, are built to enforce their semantics, such as literally not being able to copy a unique_ptr, but are able to move it, and copying a shared_ptr being allowed and increasing the reference count of the object.

Yes - they are just simple classes, but using them as intended does avoid a lot of common programmer memory management mistakes, and highly adds to the readability of your program, and ability to reason about ownership, since use of these types rather than raw pointers in effect documents who the owner(s) are, and enforces that this documentation is the reality.