Search code examples
c++arraysboostshared-ptrmake-shared

What is make_shared of unknown size?


In this answer T.C. states

boost::make_shared etc. support array types - either one of unknown size, or one of fixed size

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

First, how can make_shared support an array type of unknown size? I would think the array size is required.

Second, what is the difference between sh_arr2 and sh_arr3? Both seem to be creating an array of int size 30.


Solution

  • The example isn't that great. By an array of unknown size they presumably mean it can be invoked in the following way:

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

    Since arr2_size can be dynamically defined it can be considered 'unknown'.

    Secondly they do both create an array of size 30, but sh_arr3 contains the size in the type itself which will allow the compiler to emit warnings if access goes outside of the bounds. The type without an explicit size will not be able to detect those cases.