Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Since C++17 supports shared_ptr of array, does this mean that an explicit deleter for T[] is no longer required in both ctor and reset?

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?
like image 555
sandthorn Avatar asked Aug 03 '17 04:08

sandthorn


People also ask

Do I have to delete shared_ptr?

So no, you shouldn't. The purpose of shared_ptr is to manage an object that no one "person" has the right or responsibility to delete, because there could be others sharing ownership. So you shouldn't ever want to, either.

What happens when shared_ptr goes out of scope?

The smart pointer has an internal counter which is decreased each time that a std::shared_ptr , pointing to the same resource, goes out of scope – this technique is called reference counting. When the last shared pointer is destroyed, the counter goes to zero, and the memory is deallocated.

Why would you choose shared_ptr instead of unique_ptr?

Use unique_ptr when if you want to have single ownership(Exclusive) of resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. Use shared_ptr if you want to share ownership of resource .


1 Answers

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.

like image 111
Frank Avatar answered Nov 15 '22 14:11

Frank