为什么使用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]’
答案 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>
。