14

When create shared_ptr using a separated allocation, an explicit delete function must be provided in C++14 ctor and reset member function.

using std::string;
using std::shared_ptr;
using std::default_delete;
int arr_size{};
...


auto string_arr_sptr_cpp14 = 
         shared_ptr<string[]>(new string[arr_size], default_delete<string[]>() );
string_arr_sptr_cpp14.reset(new string[arr_size], default_delete<string[]>() );
// define an explicit deleter, 
// or otherwise, "delete ptr;" will internally be used incorrectly!

By supporting shared_ptr of array feature in C++17, would those be no longer required in both ctor and reset?

auto string_arr_sptr_cpp17 = shared_ptr<string[]>(new string[arr_size]);
string_arr_sptr_cpp14.reset(new string[arr_size]);
// deduced delete function calls "delete[] ptr;" correctly now?
sandthorn
  • 2,770
  • 1
  • 15
  • 59

1 Answers1

5

You are correct, shared_ptr<T[]> now naturally handles calling delete[] properly.

http://eel.is/c++draft/util.smartptr.shared#const-5

Effects: When T is not an array type, constructs a shared_­ptr object that owns the pointer p. Otherwise, constructs a shared_­ptr that owns p and a deleter of an unspecified type that calls delete[] p.

And as far as reset() goes:

http://eel.is/c++draft/util.smartptr.shared#mod-3

Equivalent to shared_­ptr(p).swap(*this).

Which will transfer the specification-required custom deleter.