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

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

+3
source share
4 answers

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.

operator[] , , .

, boost::scoped_array.

+11

std::auto_ptr .

,

std::auto_ptr<T> temp = new T(capacity); // T=int, capacity=5

int capacity. , , , .

+2

auto_ptr ; delete ( delete[]) .

, ( ), , . , , , ( ). for .

+1

auto_ptr, . , delete , delete[], , .

, , . Boost scoped_array, std::auto_ptr , new[].

+1
source

All Articles