c++ - 为什么在 std::auto_ptr 上不允许使用 operator []

标签 c++ visual-c++-2010 auto-ptr

为什么 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>”未定义此运算符或转换为预定义运算符可接受的类型

最佳答案

原因是 auto_ptr 将使用 delete 而不是 delete[] 释放内容,所以 auto_ptr 不适用于处理堆分配数组(使用 new[] 构造),仅适用于处理使用 new 构造的单个堆分配数组。

支持 operator[] 会鼓励开发人员将它用于数组,并且会错误地给人一种印象,即该类型可以支持数组,而实际上它不能。

如果你想要一个类似智能指针的数组类,使用boost::scoped_array .

关于c++ - 为什么在 std::auto_ptr 上不允许使用 operator [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5346389/

相关文章:

c++ - C++ 的性能问题(使用 VC++ 2010): at runtime, 我的程序似乎随机等待了一段时间

c++ - 在动态分配的数组上使用 auto_ptr 的正确方法是什么?

c++ - Qt 找不到 Qt5Core Qt5Widgets 等

c++ - #ifdef VALUE 与 #if Defined (VALUE) 之间有什么区别

c++ - 如何从类中访问函数?

c++ - C++11 VC++2010 中的线程

c++ - 如何缩放到 SDL 中的分辨率?

c++ - 警告 C6269 : Possibly incorrect order of operations: dereference ignored

c++ - std::auto_ptr 和 boost::shared_ptr 的语义

c++ - 如何使用 std::auto_ptr 作为函数的参数?