gpt4 book ai didi

c++ - 重新分配std::unique_ptr时是否释放内存?

转载 作者:行者123 更新时间:2023-12-01 14:33:26 26 4
gpt4 key购买 nike

给定以下内容:

{
std::unique_ptr<char[]> foo;
foo = std::make_unique<char[]>(100);
foo = std::make_unique<char[]>(200);
}
在第二次调用中重新分配foo时,第一次调用make_unique分配的内存是否被释放?

最佳答案

此代码没有泄漏。从其他分配给它的operator=转移所有权时,std::unique_ptr Deleter 将调用现有内存的delete[](在本示例中为unique_ptr)。
每个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)

关于c++ - 重新分配std::unique_ptr时是否释放内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63420400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com