Does unique_ptr::release() call the destructor?

Zeukis picture Zeukis · Sep 1, 2014 · Viewed 70.8k times · Source

Is this code correct?

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

Is it equivalent to delete of a raw pointer?

Answer

Mike Seymour picture Mike Seymour · Sep 1, 2014

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