Is this code correct?
auto v = make_unique<int>(12);
v.release(); // is this possible?
Is it equivalent to delete
of a raw pointer?
Yes. Well the unique ptr has a function object that by default invokes delete on the pointed to object, which calls the destructor. You can change the type of that default deleter to do almost anything.
std::unique_ptr::releaseReleases ownership of its stored pointer, by returning its value and replacing it with a null pointer. This call does not destroy the managed object, but the unique_ptr object is released from the responsibility of deleting the object.
The smart pointer destructor contains the call to delete, and because the smart pointer is declared on the stack, its destructor is invoked when the smart pointer goes out of scope, even if an exception is thrown somewhere further up the stack.
unique_ptr objects automatically delete the object they manage (using a deleter) as soon as they themselves are destroyed, or as soon as their value changes either by an assignment operation or by an explicit call to unique_ptr::reset.
No, the code causes a memory leak. release
is used to release ownership of the managed object without deleting it:
auto v = make_unique<int>(12); // manages the object
int * raw = v.release(); // pointer to no-longer-managed object
delete raw; // needs manual deletion
Don't do this unless you have a good reason to juggle raw memory without a safety net.
To delete the object, use reset
.
auto v = make_unique<int>(12); // manages the object
v.reset(); // delete the object, leaving v empty
Is this code correct?
No. Use std::unique_ptr<>::reset()
to delete the internal raw pointer:
auto v = std::make_unique<int>(12);
v.reset(); // deletes the raw pointer
After that is done, std::unique_ptr<>::get()
will return nullptr
(unless you provided a non-nullptr
parameter to std::unique_ptr<>::reset()
).
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