Search code examples
c++memorymemory-leakssmart-pointersunique-ptr

Does memory get freed when reassigning std::unique_ptr?


Given the following:

{
    std::unique_ptr<char[]> foo;
    foo = std::make_unique<char[]>(100);
    foo = std::make_unique<char[]>(200);
}

Does the memory allocated in the first call to make_unique get freed when reassigning foo with the second call?


Solution

  • There is no leak in this code. operator= for std::unique_ptr will call the Deleter (in this example, delete[]) for the existing memory when transferring ownership from another unique_ptr that is being assigned to it.

    Per cppreference:

    std::unique_ptr<T,Deleter>::operator=

    Transfers ownership from r to *this as if by calling reset(r.release()) followed by an assignment of get_deleter() from std::forward<E>(r.get_deleter()).

    std::unique_ptr<T,Deleter>::reset

    Given current_ptr, the pointer that was managed by *this, performs the following actions, in this order:

    • Saves a copy of the current pointer old_ptr = current_ptr
    • Overwrites the current pointer with the argument current_ptr = ptr
    • If the old pointer was non-empty, deletes the previously managed object
      if(old_ptr) get_deleter()(old_ptr)