Search code examples
c++visual-c++-2010auto-ptr

Why operator [] is not allowed on std::auto_ptr


Why operator [] is 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 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


Solution

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