#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.
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!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With