c++ - std::unique_ptr 是为数组分配内存的错误工具吗?

标签 c++ c++11 memory-management smart-pointers unique-ptr

我有一组(例如)uint8_t

std::unique_ptr 是用来管理内存中这个对象的错误工具吗?

例如,

std::unique_ptr<uint8_t> data(new uint8_t[100]);

这会产生未定义的行为吗?

我想要一个智能指针对象来为我管理一些分配的内存。 std::vector 并不理想,因为它是一个动态对象。 std::array 也不好,因为分配的大小在编译时是未知的。我无法使用 [currently, 2016-03-06] 实验性 std::dynarray,因为它在 Visual Studio 2013 上尚不可用。

不幸的是,我必须遵守 VS2013,因为规则。

最佳答案

您使用 unique_ptr 的方式确实会导致未定义的行为,因为它会 delete 托管指针,但您希望它是 delete []d 代替。 unique_ptr 有一个 partial specialization for array types来处理这样的情况。你需要的是

std::unique_ptr<uint8_t[]> data(new uint8_t[100]);

您还可以使用 make_unique为此

auto data = std::make_unique<uint8_t[]>(100);

然而,两者之间存在细微差别。使用 make_unique 会将数组初始化为零,而第一种方法不会。

关于c++ - std::unique_ptr 是为数组分配内存的错误工具吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35829647/

相关文章:

c++ - 如何将同一行中的值分组为一对?

c++ - std::deque 错误?

安卓 2.2 : best way to read small blocks of binary data from big files?

c++ - 当 C++ 分配器被销毁/复制/move 时,它应该如何处理其分配的内存?

java - 垃圾收集器与池

c# - .NET 和 PCL(点云库)

c++ - Vista 中的 C/C++ 编程

c++ - LLVM:如何在运行时跟踪无类型语言的 Value* 的数据类型?

c++ - C++ 迭代器段错误

c++ - std::list 删除中的意外结果 (C++)