Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing array of shared_ptr

Tags:

c++

#include <memory>

int main()
{
   std::shared_ptr<double> array (new double [256], [](double * d){
      delete [] d;
   });
}

I made a shared_ptr pointing into an array of doubles which has its own custom deleter.

Now how can I access the array? Let's say I wish to access the array at index 1. I tried the usual "bracket method" but I get errors.

The word array points to its first element by default, but what if I want to access the 2nd element? Using increments and bracket gives me the "no match for operator" error.

Can someone explain to me what's happening under the hood?

I am asking this for research purposes, despite being aware that unique_ptr and vector will do a better job.

like image 778
Carlos Miguel Colanta Avatar asked Jun 11 '15 12:06

Carlos Miguel Colanta


1 Answers

The bracket notation is defined to work with pointer types (and you're right that, given array array, the expression array decays to an expression with such a type which points to the first element) but, despite its function, std::shared_ptr is not a pointer type.

You would have to obtain the raw pointer first:

array.get()[n];

Where n is, of course, a valid array subscript.

This is also the case with std::unique_ptr (though note that, in that case, you do not need to supply your own deleter!).

like image 70
Lightness Races in Orbit Avatar answered Nov 22 '22 10:11

Lightness Races in Orbit