Search code examples
c++unique-ptr

Does unique_ptr::release() call the destructor?


Is this code correct?

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

Is it equivalent to delete of a raw pointer?


Solution

  • 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