gpt4 book ai didi

c++ - 指向数组的unique_ptr在调用release()后会自动释放动态内存吗?

转载 作者:行者123 更新时间:2023-12-02 00:08:35 24 4
gpt4 key购买 nike

据我所知,调用std::unique_ptr<T,Deleter>::release仅转移所有权,不会释放动态内存。

来自C++ Primer 5th:

p2.release(); // WRONG: p2 won't free the memory and we've lost the pointer
auto p = p2.release(); // ok, but we must remember to delete(p)

但是几页之后它写道:

The library provides a version of unique_ptr that can manage arrays allocated by new. To use a unique_ptr to manage a dynamic array, we must include a pair of empty brackets after the object type:

// up points to an array of ten uninitialized ints
unique_ptr<int[]> up(new int[10]);
up.release(); // automatically uses delete[] to destroy its pointer

The brackets in the type specifier (<int[]>) say that up points not to an int but to an array of ints. Because up points to an array, when up destroys the pointer it manages, it will automatically use delete[].

<小时/>

那么 std::unique_ptr<T,Deleter>::releas 是真的吗?对动态分配的数组的处理方式有所不同,即在调用release()后自动释放分配的内存。 ?如果这是真的,那么它也表明不能转移动态数组的所有权。到目前为止我在网上找不到任何权威的引用资料。

最佳答案

我看了一点,我猜这只是作者的一个错误。 cppreference.com makes no reference to any array specialization for release 。为了确保这一点,我继续检查了 libc++(LLVM 标准库的实现)的源代码。 This is the implementation for std::unique_ptr<T[], Deleter>::release 。正如你所看到的,它没有调用 delete[] 。我的猜测是作者打算写 up.reset(); ,如this does free the memory .

关于c++ - 指向数组的unique_ptr在调用release()后会自动释放动态内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59279670/

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