【发布时间】:2011-07-17 19:29:52
【问题描述】:
为什么 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;
}
在 Microsoft Visual C++ 2010 上编译。
错误: 错误 C2676:二进制 '[' : 'std::auto_ptr<_ty>' 未定义此运算符或转换为预定义运算符可接受的类型
【问题讨论】:
-
顺便说一下,
capacity的参数类型应该不是T。 -
您能详细说明为什么
std::vector<T>不能满足您的需求吗? -
@fbrereto - 刚刚学习
std::auto_ptr。并对这个错误感到震惊和惊讶。这只是一个学习部分。 -
请注意,在 C++0x 中,
std::unique_ptr(std::auto_ptr的高级替代品)专门用于数组类型。
标签: c++ visual-c++-2010 auto-ptr