Search code examples
c++arrayspointersshared

Using make_shared with char[] or int[]


Can you tell me if this works in VS2015 ?

shared_ptr< char> buffer( make_shared< array< char,10>>() , [] (char *p){delete[] p; } );

or

shared_ptr< char> buffer( make_shared< array< int,10>>() ,default_delete< int[]>());

Solution

  • Visual Studio 2015 doesn't support the C++17 standard. Prior to C++17 standard you can't have the std::shared_ptr<T[]> pointer. But even in C++17 the std::make_shared function doesn't support array types so you would have to use the boost::make_shared instead. Another alternative is to use the unique pointer in combination with the std::make_unique which does support the array types. This again might not be a good idea as pointed out by Scot Meyers in his "Effective Modern C++" book:

    The existence of std::unique_ptr for arrays should be of only intellectual interest to you, because std::array, std::vector, and std::string are virtually always better data structure choices than raw arrays.