Mah*_*esh 3 c++ auto-ptr visual-c++-2010
为什么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;
}
Run Code Online (Sandbox Code Playgroud)
在Microsoft Visual C++ 2010上编译.
错误:错误C2676:二进制'[':'std :: auto_ptr <_Ty>'未定义此运算符或转换为预定义运算符可接受的类型
Mic*_*yan 11
原因是auto_ptr将使用delete而不是使用内容来释放内容delete[],因此auto_ptr不适合处理堆分配的数组(由其构造new[]),并且仅适用于处理由其构造的单个堆分配数组new.
支持operator[]会鼓励开发人员将它用于数组,并且会错误地给人一种类型可以支持数组的印象,实际上它不能.
如果你想要一个类似smartpointer的数组类,请使用boost :: scoped_array.
| 归档时间: |
|
| 查看次数: |
972 次 |
| 最近记录: |