What are recommended uses of a std::unique_ptr
as to specifically where, when, and how is it is best used?
I discovered:
About unique_ptr performances
I already know:
std::unique_ptr
was developed in C++11 as a replacement for std::auto_ptr
std::unique_ptr
has no reference counting and "owns" object it points tostd::unique_ptr
std::unique_ptr
is the go to structureWhat I would like to know:
std::unique_ptr
ever preferable (other than uniqueness) to somethingstd::unique_ptr
less favorablestd::shared_ptr
would suffice for dynamic memory management in nearly every situation, why does having at my disposal a std::unique_ptr
matter (again, otherUse unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.
A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.
An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.
Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.
In theory, you should use unique_ptr
for all pointers unless you know you want to share it, in which case you should use shared_ptr
. The reason is that unique_ptr
has less overhead since it doesn't count references.
However, a unique_ptr
is movable but not copyable, so using one as a member variable can require you to write more code (eg a move constructor), passing one by value means you'll need to use std::move
and so on. As a result some people use shared_ptr
out of laziness, because it's just easier, and the perf difference may not be significant for their app.
Finally a raw pointer is fine for observation - pointer uses that can never affect lifetime. Careful choice of the right pointer type can give those who read your code a good understanding of what you are doing. For more, see Herb Sutter's essay, Elements of C++ Style, specifically the "no delete" section.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With