Doesn't std::unique_ptr::get
defeat the purpose of having a unique_ptr in the first place? I would have expected this function to change its state so it holds no more pointer. Is there an actual useful use of std::unique_ptr::get?
In short: 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.
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.
It is recommended to use the 'make_unique/make_shared' function to create smart pointers. The analyzer recommends that you create a smart pointer by calling the 'make_unique' / 'make_shared' function rather than by calling a constructor accepting a raw pointer to the resource as a parameter.
unique_ptr. An unique_ptr has exclusive ownership of the object it points to and will destroy the object when the pointer goes out of scope.
std::unique_ptr
provides unique ownership semantics safely. However that doesn't rule out the need for non-owning pointers. std::shared_ptr
has a non-owning counterpart, std::weak_ptr
. Raw pointers operate as std::unique_ptr
's non-owning counterpart.
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