可以编译这段简单的代码。
unique_ptr<list<int>> map1(new list<int>[10]);
但是运行时会导致seg falut。
malloc: * error for object 0x7fe02a4032e8: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug
但是这段代码成功运行了。
unique_ptr<int> map2(new int[10]);
为什么不能使用 unique_ptr 创建列表数组?
提前致谢。
最佳答案
您需要为动态分配的数组使用 unique_ptr 版本:
std::unique_ptr<std::list<int>[]> map1(new std::list<int>[10]);
^^ ~~~~~ !
参见此处:http://en.cppreference.com/w/cpp/memory/unique_ptr :
template <
class T,
class Deleter
> class unique_ptr<T[], Deleter>;
您还可以使用 std::make_unique (如评论中所建议的那样)你会得到编译错误而不是 UB,因为它的接口(interface)可以防止它:
std::unique_ptr<std::list<int>[]> up1 = std::make_unique<std::list<int>[]>(10);
auto up2 = std::make_unique<std::list<int>[]>(10);
[编辑]
However this code successfully ran.
unique_ptr map2(new int[10]);
它在上面的代码中仍然是未定义的行为,它可能会工作或可能导致段错误。上面的 unique_ptr 接受任何指针,但在析构期间总是调用 delete
。在指向动态分配数组的指针上调用 delete
是 UB。这就是您需要调用 delete[]
的原因,这就是 unique_ptr
为动态分配的数组所做的。
关于c++ - 我无法制作 list<int> 数组的 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36626960/