Why is the [] operator not allowed on std :: auto_ptr?
#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 in Microsoft Visual C ++ 2010.
Error: Error C2676: binary '[': 'std :: auto_ptr <_Ty>' does not define this operator or conversion to a type acceptable for the predefined operator
The reason is that it will auto_ptrfree content using deleteinstead delete[], and therefore auto_ptrnot suitable for processing arrays allocated by a heap (built with new[]), and only suitable for managing single arrays allocated by heaps that were built using new.
auto_ptr
delete
delete[]
new[]
new
operator[] , , .
operator[]
, boost::scoped_array.
std::auto_ptr .
std::auto_ptr
,
std::auto_ptr<T> temp = new T(capacity); // T=int, capacity=5
int capacity. , , , .
int
capacity
auto_ptr ; delete ( delete[]) .
, ( ), , . , , , ( ). for .
auto_ptr, . , delete , delete[], , .
, , . Boost scoped_array, std::auto_ptr , new[].
scoped_array