Benefits of using BOOST shared_array over shared_ptr

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 09:57:02

问题


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.

According to the BOOST doc Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array.

So I'm just wondering now what purpose user should use shared_array instead of shared_ptr.


回答1:


Before boost 1.53, shared_ptr is to be used for a pointer to a single object.

After 1.53, since shared_ptr can be used for array types, I think it's pretty much the same as shared_array.

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.

See shared_ptr to an array : should it be used? as reference for the difference.

So if you want your code compatible with C++11 and use std::shared_ptr instead, you need to use it carefully. Because:

  • 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
    
  • 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
    

The syntax of shared_ptr in std and boost are different and not compatible.

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.



来源:https://stackoverflow.com/questions/25968849/benefits-of-using-boost-shared-array-over-shared-ptr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!