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?
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 callingreset(r.release())
followed by an assignment ofget_deleter()
fromstd::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)