为什么将unique_ptr与数组一起使用会导致编译错误?

时间:2014-04-03 12:35:41

标签: c++ arrays unique-ptr

为什么使用unique_ptr <string> items;而不是原始指针string *items;抛出编译错误。

#include <iostream>
#include <memory>
using namespace std;

class myarray
{
  private:
    unique_ptr <string> items;
    //string *items;
  public:
    myarray (int size=20) : items (new string [size] ) {}

    string& operator[] (const int index)
    {
      return items[index];
    }
};


int main()
{
  myarray m1(200);
  myarray m2;
  m1[19] = "test";
  cout << m1[19];
  return 0;
}

错误:

subscript2.cpp: In member function ‘std::string& myarray::operator[](int)’:
subscript2.cpp:15: error: no match for ‘operator[]’ in ‘((myarray*)this)->myarray::items[index]’

3 个答案:

答案 0 :(得分:6)

如果你想要一个指向动态分配的数组字符串的unique_ptr指针,你可能想要使用unique_ptr<T[]>形式,即:

unique_ptr<string[]> items;

事实上:

  • unique_ptr<T>是指向T单个实例的指针
  • unique_ptr<T[]>是指向T数组的指针

答案 1 :(得分:4)

如果您需要unique_ptr到一个字符串数组,那么您需要将其声明为:

unique_ptr <string[]> items;

答案 2 :(得分:2)

在原始指针的情况下,你愚弄编译器(和运行时),认为*items是字符串对象数组中的第0个元素。即使您为字符串分配了内存,要为index使用除零值之外的任何内容都将是未定义的行为。 (items[0]*items相同。)

在使用unique_ptr版本时,编译器实际上正在帮助您。

如果您想要一个字符串数组,请改用std::vector<std::string>