Does unique_ptr::release() call the destructor?

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


Is this code correct?

It is not, and will leak.

release() just let the calling code take back ownership of the memory that the unique_ptr held until it was called. If you don't assign the pointer returned by release(), you'll just have a leak.

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.

So you should have a very good reason to perform manual memory management on an automatic memory management object.

Tags:

C++

Unique Ptr