I wonder what the rationale is behind the fact, that std::shared_ptr
does not define the []
operator for arrays. In particular why does std::unique_ptr
feature this operator but not std::shared_ptr
?
The ownership of an object can only be shared with another shared_ptr by copy constructing or copy assigning its value to another shared_ptr . Constructing a new shared_ptr using the raw underlying pointer owned by another shared_ptr leads to undefined behavior.
What is the technical problem with std::shared_ptr::unique() that is the reason for its deprecation in C++17? this function is deprecated as of C++17 because use_count is only an approximation in multi-threaded environment.
Use unique_ptr when you want to have single ownership(Exclusive) of the 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. A shared_ptr is a container for raw pointers.
std::shared_ptr is not thread safe. A shared pointer is a pair of two pointers, one to the object and one to a control block (holding the ref counter, links to weak pointers ...).
std::unique_ptr
only defines operator[]
in a specialization for arrays: std::unique_ptr<T[]>
. For non-array pointers, the operator[] doesn't make much sense anyways (only [0]
).
Such a specialization for std::shared_ptr
is missing (in C++11), which is discussed in the related question: Why isn't there a std::shared_ptr<T[]> specialisation?
You should not use a non-array smart pointer with array allocation, unless you provide a custom deleter. In particular, unique_ptr<int> p = new int[10]
is bad, since it calls delete
instead of delete[]
. Use unique_ptr<int[]>
instead, which calls delete[]
. (And this one implements operator[]
). If you're using shared_ptr
to hold a T[]
, you need to use a custom deleter. See also shared_ptr to an array : should it be used? -- but it doesn't provide operator[]
, since it uses type erasure to distinguish between array and non-array (the smart pointer type is independent of the provided deleter).
If you wonder why there is no shared_ptr
specialization for arrays: that was a proposal, but wasn't included in the standard (mainly since you can work around by writing ptr.get() + i
for ptr[i]
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With