Reputation: 2823
#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.
Upvotes: 6
Views: 8421
Reputation: 2035
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 });
}
Upvotes: 0
Reputation: 385098
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!).
Upvotes: 11