重新分配 std::unique_ptr 时会释放内存吗?

Does memory get freed when reassigning std::unique_ptr?

鉴于以下情况:

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

第二次调用重新分配 foo 时,第一次调用 make_unique 时分配的内存是否被释放?

是的,unique_ptr 有一个数组特化,它将在 unique_ptr 超出范围时调用 array-wide 析构函数:

https://en.cppreference.com/w/cpp/memory/unique_ptr

正如您在上一个示例中所见,它创建了一个 D 数组,然后为创建的所有 D 调用析构函数。

这段代码没有漏洞。 operator= for std::unique_ptr 将在从分配给它的另一个 unique_ptr 转移所有权时为现有内存调用 Deleter(在本例中为 delete[]) .

根据 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)

你只定义了一次foo
具体来说,在范围的第一行:

std::unique_ptr<char[]> foo;

因为它是 default-initialized,调用 default-ctor,它用 nullptr 初始化。

另外两行给foo赋新值,没有re-definition会出错.

是的,如果您为 foo 分配一个新值,assignment-operator 将释放以前拥有的内存,保证。