为什么std::auto_ptr不允许使用operator []?
#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;
}
使用Microsoft Visual C++ 2010编译。
错误:错误C2676:二进制“[”:'std::auto_ptr<_Ty>'未定义此运算符或无法转换为预定义运算符可接受的类型。
capacity
的参数类型应该选择与T
不同的类型。 - fbreretostd::vector<T>
不能满足你的需求吗? - fbreretostd :: auto_ptr
。但是遇到了一个令人惊讶的错误。这只是一个学习的过程。 - Maheshstd::unique_ptr
(std::auto_ptr
的更优秀替代品)被专门用于数组类型。 - GManNickG