使用Boost的好处shared_array过的shared_ptr [英] Benefits of using BOOST shared_array over shared_ptr
问题描述
我想在我的应用程序使用 BOOST智能指针作为内存管理。但我不知道它的智能指针,我应该使用动态分配的数组的shared_ptr
或 shared_array
。
I want to use BOOST Smart pointer for memory management in my application. But I'm not sure which smart pointer should I use for dynamically allocated array shared_ptr
or shared_array
.
按照 BOOST
商务部与加速释放1.53开始,shared_ptr的可以用来容纳一个指向一个动态分配的数组。
所以我刚才不知道用途的用户应该使用什么样的 shared_array 而不是的shared_ptr 。
So I'm just wondering now what purpose user should use shared_array instead of shared_ptr.
推荐答案
提升1.53之前,的shared_ptr
是用于一个指向一个对象。
Before boost 1.53, shared_ptr
is to be used for a pointer to a single object.
1.53后,因为的shared_ptr
可用于数组类型,我认为这是pretty大致相同 shared_array
。
After 1.53, since shared_ptr
can be used for array types, I think it's pretty much the same as shared_array
.
但现在我不认为这是一个好主意,在的shared_ptr
使用数组类型,因为C ++ 11的的std :: shared_ptr的
对数组类型有点不同的行为相比,的boost :: shared_ptr的
。
But for now I don't think it's a good idea to use array type in shared_ptr
, because C++11's std::shared_ptr
has a bit different behavior on array type compared to boost::shared_ptr
.
请参阅shared_ptr到一个数组:它应该被用来为差基准
所以,如果你希望你的code与C ++ 11兼容并使用的std :: shared_ptr的
相反,你需要仔细使用它。这是因为:
So if you want your code compatible with C++11 and use std::shared_ptr
instead, you need to use it carefully. Because:
-
code类似于下面得到编译错误(你需要一个定制删除),而升压转换器的版本就可以了。
Code look like below gets compile error (you need a custom deleter), while boost's version is OK.
std::shared_ptr<int[]> a(new int[5]); // Compile error
// You need to write like below:
std::shared_ptr<int> b(new int[5], std::default_delete<int[]>());
boost::shared_ptr<int[]> c(new int[5]); // OK
不过,如果你写code像下面,你很可能得到段故障
However, if you write code like below, you are likely to get segment fault
std::shared_ptr<T> a(new T[5]); // segment fault
boost::shared_ptr<T> b(new T[5]); // segment fault
的shared_ptr
的语法 STD
和升压
是不同的,不兼容的。
The syntax of shared_ptr
in std
and boost
are different and not compatible.
更多信息:考虑的boost :: ptr_vector 一>,这是在动态矢量分配对象pretty快速实施。仅供参考的情况下,你要这个功能。
Additional information: consider boost::ptr_vector, which is a pretty fast implementation for dynamic allocated objects in vector. Just FYI in case you want this feature.
这篇关于使用Boost的好处shared_array过的shared_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!