我经常需要在 C++ 中处理动态分配的数组,因此依赖 Boost 来处理scoped_array、shared_array 等。读完Stroustrup's C++11 FAQ后和 C++11 Reference Wiki ,我找不到 C++11 标准提供的这些动态数组包装器的合适替代品。是否有什么我忽略了,或者我必须继续依赖 Boost?
最佳答案
有一个专门化unique_ptr
,例如unique_ptr<T[]>
.
#include <iostream>
#include <memory>
struct test
{
~test() { std::cout << "test::dtor" << std::endl; }
};
int main()
{
std::unique_ptr<test[]> array(new test[3]);
}
当您运行它时,您将收到此消息。
test::dtor
test::dtor
test::dtor
<小时/>
如果您想使用shared_ptr
,你应该使用std::default_delete<T[]>
对于删除器,因为它没有像 shared_ptr<t[]>
这样的.
std::shared_ptr<test> array(new test[3], std::default_delete<test[]>());
关于c++11 - C++11 是否有像 Boost 的scoped_array 这样的动态分配数组的包装器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8624146/