Allocate char* array with boost::make_shared

Viewed 1751

To allocate a char* array I would normally write something like:

char* arr = new char[size];

How can I achieve the same thing using boost::shared_ptr (or probably boost::shared_array) and boost::make_shared?

My guesses are:

1) boost::shared_ptr<char[]> arr = boost::make_shared<char[]>(size);

2) boost::shared_ptr<char> arr = boost::make_shared<char>(size);

3) boost::shared_ptr<char> arr = boost::shared_ptr<char>(new char[size]);

The last one looks right but is it guaranteed that upon destruction delete [] arr will be called?

2 Answers

The correct one is make_shared<T[]>(n).

Bear in mind that pre-c++20 it's an extension not present in the standard library (although unique_ptr<T[]> is part of the standard).

Boost's shared_ptr will indeed call the correct deleter (naively, delete[]) for it.

Boost shared_ptr and make_shared

Boost supports array allocation and handling using shared_ptr and make_shared. According to boost's docs:

Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array. This is accomplished by using an array type (T[] or T[N]) as the template parameter. There is almost no difference between using an unsized array, T[], and a sized array, T[N]; the latter just enables operator[] to perform a range check on the index.

Just use:

shared_ptr<char[]> arr(new char[size]);
-- OR --
shared_ptr<char[]> arr = make_shared<char[]>(size);

Standard library

According to cppreference.com, The standard shared_ptr, make_shared and allocate_shared added support for arrays starting from C++20.

Related