Why using unique_ptr <string> items; instead of raw pointer string *items; throwing compilation error.
#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;
}
Error:
subscript2.cpp: In member function ‘std::string& myarray::operator[](int)’:
subscript2.cpp:15: error: no match for ‘operator[]’ in ‘((myarray*)this)->myarray::items[index]’
If you want a unique_ptr pointer to a dynamically allocated array of strings, you may want to use the unique_ptr<T[]> form, i.e.:
unique_ptr<string[]> items;
In fact:
unique_ptr<T> is a pointer to a single instance of Tunique_ptr<T[]> is a pointer to an array of TsIf you need a unique_ptr to an array of strings then you need to declare it as:
unique_ptr <string[]> items;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With