Anshuman Anshuman - 1 month ago 10
C++ Question

Shared pointer [] operator and ++ operator

Can we use [] operator or ++ with unique pointer or shared_pointer? As we use it for raw pointer

int * a = new int[10];
a[0] = 2; // We can use [] operator;



  • Is there a similar way for smart pointers?

  • If it is there should when should I use this?

  • If it is not there then Why?

  • Is it also possible for MultiDimensional Array ?


Answer

Both std::unique_ptr and std::shared_ptr provide operator[] for indexed access to the stored array. You can use them if what they're managing is array.

operator[] provides access to elements of an array managed by a unique_ptr.

e.g.

std::unique_ptr<int[]> a(new int[10]);
a[0] = 2; // We can use [] operator;

Note the index shall be less than the number of elements in the array; otherwise, the behavior is undefined.

And I'll suggest you to use std::vector or std::array if you just want an array.

Comments