Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does unique_ptr::release() call the destructor?

Tags:

c++

unique-ptr

Is this code correct?

auto v =  make_unique<int>(12);
v.release();     // is this possible?

Is it equivalent to delete of a raw pointer?

like image 479
Zeukis Avatar asked Sep 01 '14 15:09

Zeukis


People also ask

Does unique_ptr call destructor?

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.

What does unique_ptr release do?

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.

Do smart pointers call destructor?

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.

Does unique_ptr call Delete?

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.


2 Answers

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
like image 101
Mike Seymour Avatar answered Oct 13 '22 10:10

Mike Seymour


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()).

like image 35
Johann Gerell Avatar answered Oct 13 '22 12:10

Johann Gerell