Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why using unique_ptr with arrays causes compilation error?

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]’
like image 845
Devesh Agrawal Avatar asked Nov 28 '25 16:11

Devesh Agrawal


2 Answers

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
like image 108
Mr.C64 Avatar answered Dec 01 '25 06:12

Mr.C64


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

unique_ptr <string[]> items;
like image 45
Marius Bancila Avatar answered Dec 01 '25 06:12

Marius Bancila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!