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

时间:2016-03-06 16:52:00

标签: 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也不好,因为在编译时不知道分配的大小。我无法使用[目前,2016-03-06]实验std::dynarray,因为Visual Studio 2013尚未提供此功能。

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

2 个答案:

答案 0 :(得分:12)

您使用unique_ptr的方式确实会导致未定义的行为,因为它会delete托管指针,但您希望它是delete[] d。 unique_ptrpartial 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将零初始化数组,而第一种方法则不会。

答案 1 :(得分:2)

当然unique_ptr因为您使用它是不正确的,因为它会调用delete而不是delete[]来释放内存。

这种情况的正常解决方案是std::vector:它分配和管理你的内存,并提供一个相当强大的界面。您说您不想使用vector,因为我推断您True, but would be risky to expose that functionality to the user.将您的容器类型的实现细节暴露给您的类的接口。 那是你真正的问题。

因此,请使用vector管理内存,但不要直接在类界面中公开vector