2

I'm not able to understand the boost documentation on how to use make_shared and allocate_shared to initialize shared arrays and pointers:

shared_ptr<int> p_int(new int); // OK
shared_ptr<int> p_int2 = make_shared<int>(); // OK
shared_ptr<int> p_int3 = allocate_shared(int);  // ??


shared_array<int> sh_arr(new int[30]); // OK
shared_array<int> sh_arr2 = make_shared<int[]>(30); // ??
shared_array<int> sh_arr3 = allocate_shared<int[]>(30); // ??

I'm trying to learn the correct syntax to initialize the above variables commented as // ??

codekiddy
  • 5,897
  • 9
  • 50
  • 80

1 Answers1

6

allocate_shared is used just like make_shared, except that you pass an allocator as the first argument.

boost::shared_ptr<int> p_int(new int);
boost::shared_ptr<int> p_int2 = boost::make_shared<int>();

MyAllocator<int> alloc;
boost::shared_ptr<int> p_int3 = boost::allocate_shared<int>(alloc);

There is no make function for boost::shared_array, so the only way to make one is allocating the memory manually:

boost::shared_array<int> sh_arr(new int[30]);

But boost::make_shared etc. support array types - either one of unknown size, or one of fixed size - in both cases a boost::shared_ptr is returned:

boost::shared_ptr<int[]> sh_arr2 = boost::make_shared<int[]>(30);
boost::shared_ptr<int[30]> sh_arr3 = boost::make_shared<int[30]>();

Note that std::shared_ptr does not support arrays at this time.

T.C.
  • 133,968
  • 17
  • 288
  • 421
  • **boost::shared_ptr sh_arr2 = boost::make_shared(30);** will memory be freed correctly in this case? and what do you mean by "does not support arrays at this time"? because I was able to fill in each element and access each one with for loop and [] operator... – codekiddy Mar 08 '15 at 18:16
  • 2
    @codekiddy 1) If you are using a sufficiently recent version of boost (1.53 or later), then the memory will be freed correctly. 2) I was talking about `std::shared_ptr`, the one that came in the standard library. That one doesn't support arrays as of C++14 (a proposal to add array support was voted into a draft technical specification). – T.C. Mar 08 '15 at 18:32
  • Oh, **std::shared_ptr**, I see now, Thank you for additional info. very useful! – codekiddy Mar 08 '15 at 18:46