c++ - 我无法制作 list<int> 数组的 unique_ptr

标签 c++ arrays list stl unique-ptr

可以编译这段简单的代码。

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/

相关文章:

c++ - 如何在同一个程序中创建多个套接字。?

java - Java 与 C++ 中的对象数组

python - 如何在不返回函数的情况下访问函数内部的列表?

python - 在 Python 中,是否有一种紧凑的方法来打印满足条件的列表中的那些变量的名称?

c++ - 从 C++ 文件中读取 ASCII 码和二进制码

c++ - 过滤 QStandardItemModel 或 QTreeView 中的项目

c++ - Fruchterman Reingold 布局不收敛

arrays - 在 bash 数组中获取 shell 命令的输出

java - 在 Java 中为链中的变量赋值

string - 如何在haskell中组合两种不同类型的列表