Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no [] operator for std::shared_ptr? [duplicate]

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?

like image 901
Haatschii Avatar asked Jan 07 '15 12:01

Haatschii


People also ask

Can you copy a 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.

Why is shared_ptr unique deprecated?

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.

Why would you choose shared_ptr instead of Unique_ptr?

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.

Is shared_ptr copy thread safe?

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 ...).


1 Answers

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]).

like image 194
leemes Avatar answered Oct 04 '22 02:10

leemes