3

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]’

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

Comments

4

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

unique_ptr <string[]> items;

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.