C++11 是否有动态分配数组的包装器,比如 Boost 的 scoped_array? [英] Does C++11 have wrappers for dynamically-allocated arrays like Boost's scoped_array?
问题描述
我经常需要在 C++ 中处理动态分配的数组,因此依赖 Boost 来处理 scoped_array、shared_array 等.通读 Stroustrup 的 C++11 FAQ 和 C++11 参考 Wiki,我找不到 C++11 提供的这些动态数组包装器的合适替代品标准.有什么我忽略的地方,还是我必须继续依赖 Boost?
I often need to deal with dynamically-allocated arrays in C++, and hence rely on Boost for scoped_array, shared_array, and the like. After reading through Stroustrup's C++11 FAQ and the C++11 Reference Wiki, I could not find a suitable replacement for these dynamic array wrappers that is provided by the C++11 standard. Is there something that I have overlooked, or do I have to continue relying on Boost?
推荐答案
unique_ptr
有一个特化,比如 unique_ptr
.
There is a specialization of unique_ptr
, like 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]);
}
当您运行它时,您将收到此消息.
When you run it, you will get this messages.
test::dtor
test::dtor
test::dtor
<小时>
如果你想使用 shared_ptr
,你应该使用 std::default_delete<T[]>
作为删除器,因为它没有像 这样的shared_ptr
.
If you want to use shared_ptr
, you should use std::default_delete<T[]>
for deleter since it doesn't have one like shared_ptr<t[]>
.
std::shared_ptr<test> array(new test[3], std::default_delete<test[]>());
这篇关于C++11 是否有动态分配数组的包装器,比如 Boost 的 scoped_array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!