Can you make a std::shared_ptr point to an array? For example,
std::shared_ptr<int> sp(new int[10]);
If not, then why not? One reason I am already aware of is one can not increment/decrement the std::shared_ptr. Hence it cannot be used like a normal pointer to an array.
With C++17,
shared_ptrcan be used to manage a dynamically allocated array. Theshared_ptrtemplate argument in this case must beT[N]orT[]. So you may writeFrom n4659, [util.smartptr.shared.const]
To support this, the member type
element_typeis now defined asArray elements can be access using
operator[]Prior to C++17,
shared_ptrcould not be used to manage dynamically allocated arrays. By default,shared_ptrwill calldeleteon the managed object when no more references remain to it. However, when you allocate usingnew[]you need to calldelete[], and notdelete, to free the resource.In order to correctly use
shared_ptrwith an array, you must supply a custom deleter.Create the shared_ptr as follows:
Now
shared_ptrwill correctly calldelete[]when destroying the managed object.The custom deleter above may be replaced by
the
std::default_deletepartial specialization for array typesa lambda expression
Also, unless you actually need share onwership of the managed object, a
unique_ptris better suited for this task, since it has a partial specialization for array types.Changes introduced by the C++ Extensions for Library Fundamentals
Another pre-C++17 alternative to the ones listed above was provided by the Library Fundamentals Technical Specification, which augmented
shared_ptrto allow it to work out of the box for the cases when it owns an array of objects. The current draft of theshared_ptrchanges slated for this TS can be found in N4082. These changes will be accessible via thestd::experimentalnamespace, and included in the<experimental/memory>header. A few of the relevant changes to supportshared_ptrfor arrays are:— The definition of the member type
element_typechanges— Member
operator[]is being added— Unlike the
unique_ptrpartial specialization for arrays, bothshared_ptr<T[]>andshared_ptr<T[N]>will be valid and both will result indelete[]being called on the managed array of objects.