Does unique_ptr::release() call the destructor?

前端 未结 5 868
后悔当初
后悔当初 2021-01-30 01:58

Is this code correct?

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

Is it equivalent to delete of a

5条回答
  •  醉话见心
    2021-01-30 02:51

    No, the code causes a memory leak. release is used to release ownership of the managed object without deleting it:

    auto v = make_unique(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(12);  // manages the object
    v.reset();                      // delete the object, leaving v empty
    

提交回复
热议问题