Advantages of using BOOST shared_array over shared_ptr

I want to use BOOST Smart pointer to manage memory in my application. But I'm not sure which smart pointer should be used for a dynamically allocated array shared_ptror shared_array.

According to BOOSTdoc Starting from version 1.53 of Boost, shared_ptr can be used to store a pointer to a dynamically allocated array.

So I'm just wondering which user should use shared_array instead of shared_ptr .

+4
source share
1 answer

Before boost 1.53, it shared_ptrshould be used for a pointer to a single object.

After 1.53, since it shared_ptrcan be used for array types, I think this is almost the same as shared_array.

But at the moment, I do not consider it appropriate to use an array type in shared_ptr, because C ++ 11 std::shared_ptrhas a slightly different behavior in terms of array type compared to boost::shared_ptr.

See shared_ptr in an array: should I use it? as a reference for a difference.

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

  • , , ( ), .

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

    std::shared_ptr<T> a(new T[5]); // segment fault
    boost::shared_ptr<T> b(new T[5]); // segment fault
    

shared_ptr std boost .

: boost:: ptr_vector, . FYI, .

+6

All Articles