Alex Rivera | Logout

Double (two-dimensional) array using std::unique_ptr

Asked 2012-03-20T20:19:25.037
19

I have a double array allocated by pointer to pointer.

  // pointer to pointer
  int **x = new int *[5];   // allocation
  for (i=0; i<5; i++){
      x[i] = new int[2];
  }

  for (i=0; i<5; i++){      // assignment
      for (j=0; j<2; j++){
          x[i][j] = i+j;
      }
  }

  for (i=0; i<5; i++)   // deallocation
      delete x[i];
  delete x;

I am trying to do this using unique_ptr:

std::unique_ptr<std::unique_ptr<int>[]> a(new std::unique_ptr<int>[5]);
  for (i=0; i<5; i++)
      a[i] = new int[2];

but kept getting an error saying that no operator = matches these operands. What I am doing wrong here?

Edit
Report

1 Answer

2

Your code is effectively manipulating an array of arrays of int.

In C++ you would normally want to implement it as:

std::vector<std::vector<int> > x;

This is not a good case for unique_ptr. Also, you should not need to use pointers to unique_ptr and allocate unique_ptr objects dynamically. The whole point of unique_ptr is to eliminate usage of pointers and to provide automatic allocation and deallocation of objects.

answered 2012-03-20T20:24:08.413

Your Answer