6
#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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Carlos Miguel Colanta
  • 2,685
  • 3
  • 31
  • 49
  • Sorry to ask but shouldn't it be `std::shared_ptr array (new double [256], [](double * d){ delete [] d; });` or `std::shared_ptr array (new double [256]);` in c++17 or even `std::shared_ptr array = std::make_shared(256);`? – krjw Feb 05 '19 at 15:50

2 Answers2

11

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!).

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

in C++17, support for array of shared_ptr like in unique_ptr( c++11).

int main()
{

   std::shared_ptr<double[]> array1 (new double [3]{4,5,6}, [](double * d){
   delete [] d;});

   std::unique_ptr<double[]> array2 (new double [3]{4,5,6}, [](double * d){
   delete [] d });
}
Alok
  • 1,997
  • 2
  • 18
  • 30