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?
- 9,021
- 10
- 58
- 95
-
4`unique_ptr` has a specialization that manages arrays, `shared_ptr` doesn't. `operator[]` is only provided for that specialization. Are you asking why `shared_ptr` doesn't have that? – juanchopanza Jan 07 '15 at 12:46
-
2I hope this answers your question http://stackoverflow.com/questions/8947579/why-isnt-there-a-stdshared-ptrt-specialisation – Swtsvn Jan 07 '15 at 12:46
-
@juanchopanza I suppose I am. – Haatschii Jan 07 '15 at 12:57
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]).
-
2`shared_ptr` uses the `delete` _you_ provide (if you provide one); it's quite possible to provide something like `[]( T* p ) { delete[] p; }`. – James Kanze Jan 07 '15 at 13:04
-
Yeah, that's mainly regarding `unique_ptr`, since changing the deleter for that pointer changes the type (no type erasure there). And for `shared_ptr`, we already have a specialization which handles `delete[]`. – leemes Jan 07 '15 at 16:42
-
-
After working a long time on getting shared_ptr of c-style arrays to work as I wanted, I decided in the end it was just easier to make my own simple dynamic array container (that uses a smart pointer within) and then allocate a single instance of the container using make_shared instead. – mattgately Jul 21 '20 at 19:51