我有一个(例如)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,因为规则。
答案 0 :(得分:12)
您使用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
将零初始化数组,而第一种方法则不会。
答案 1 :(得分:2)
当然unique_ptr
因为您使用它是不正确的,因为它会调用delete
而不是delete[]
来释放内存。
这种情况的正常解决方案是std::vector
:它分配和管理你的内存,并提供一个相当强大的界面。您说您不想使用vector
,因为我推断您True, but would be risky to expose that functionality to the user.
将您的容器类型的实现细节暴露给您的类的接口。 那那是你真正的问题。
因此,请使用vector
管理内存,但不要直接在类界面中公开vector
。