Question

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]’
Was it helpful?

Solution

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 T
  • unique_ptr<T[]> is a pointer to an array of Ts

OTHER TIPS

If you need a unique_ptr to an array of strings then you need to declare it as:

unique_ptr <string[]> items;

In the raw pointer case, you're fooling the compiler (and runtime) into thinking that *items is the zeroth element in an array of string objects. To use anything other than a zero value for index would be undefined behaviour even if you had allocated memory for the string. (items[0] is the same as *items.)

In using the unique_ptr version, the compiler is actually helping you.

If you want an array of strings then use std::vector<std::string> instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top