问题
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
?
回答1:
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]
).
来源:https://stackoverflow.com/questions/27819809/why-is-there-no-operator-for-stdshared-ptr