Why operator [] is not allowed on std::auto_ptr
Why operator [] is not allowed on std::auto_ptr?开发者_JS百科
#include <iostream>
using namespace std ;
template <typename T>
void foo( T capacity )
{
auto_ptr<T> temp = new T[capacity];
for( size_t i=0; i<capacity; ++i )
temp[i] = i; // Error
}
int main()
{
foo<int>(5);
return 0;
}
Compiled on Microsoft Visual C++ 2010.
Error: error C2676: binary '[' : 'std::auto_ptr<_Ty>' does not define this operator or a conversion to a type acceptable to the predefined operator
The reason is that auto_ptr
will free the content using delete
instead of delete[]
, and so auto_ptr
is not suitable for handling heap-allocated arrays (constructed with new[]
) and is only suitable for handling single, heap-allocated arrays that were constructed with new
.
Supporting operator[]
would encourage developers to use it for arrays and would mistakenly give the impression that the type can support arrays when, in fact, it cannot.
If you want a smartpointer-like array class, use boost::scoped_array.
Because std::auto_ptr
is not intended to be used with arrays.
Besides, In your sample
std::auto_ptr<T> temp = new T(capacity); // T=int, capacity=5
actually allocates a single int
and initializes it with capacity
. It does not create an array of integers as you seem to have intended.
Because auto_ptr
is designed to hold a pointer to a single element; it will use delete
(specifically not delete[]
) on its destruction.
Your example is not doing what (I think) you think it does. Or at least the name capacity is misleading, because you are only allocating a single element (and assigning the value of capacity` to it). Your for loop has no sensible meaning.
auto_ptr
and other smart pointers are only intended to store a pointer to a single object. This is because they use delete
in the destructor, rather than delete[]
, which would be needed if it were storing a pointer to an array.
If you need to wrap an array of objects in a smart pointer, the standard library doesn't offer anything to help. However, Boost does offer scoped_array
, which behaves similar to std::auto_ptr
and is made to hold arrays of objects created by new[]
.
精彩评论