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

use*_*501 2 c++ memory-management smart-pointers unique-ptr c++11

我有一个(例如)uint8_ts 的数组.

std::unique_ptr用于在内存中管理此对象的错误工具是什么?

例如,

std::unique_ptr<uint8_t> data(new uint8_t[100]);
Run Code Online (Sandbox Code Playgroud)

这会产生不确定的行为吗?

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

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

Pra*_*ian 12

你使用它的unique_ptr方式确实会导致未定义的行为,因为它delete是托管指针,但你希望它是delete[]d.对数组类型unique_ptr有一个部分专门化来处理这种情况.你需要的是什么

std::unique_ptr<uint8_t[]> data(new uint8_t[100]);
Run Code Online (Sandbox Code Playgroud)

你也可以用make_unique

auto data = std::make_unique<uint8_t[]>(100);
Run Code Online (Sandbox Code Playgroud)

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