Accessing a std::array via a unique_ptr

  • A+
Category:Languages

This is just for learning purposes, I know I can just use a vector but I have

const int N = 1e3; auto my_arr = std::make_unique<std::array<int, N>>();  // To access it I have to do this - why [0][0] twice? my_arr.get()[0][0] = 1;  // Getting the size for fun std::cout << sizeof(my_arr.get()) << "/n"; // outputs 8 std::cout << sizeof(my_arr.get()[0]) << "/n"; // outputs 800000000 std::cout << sizeof(my_arr.get()[0][0]) << "/n"; // outputs 8 

I understand that .get() returns a pointer to the managed object but I don't understand why I need to do my_arr.get()[0][0] twice?

 


Well, you don't have to do that, but it works.

my_arr.get() returns a std::array<int,N>*

Like any pointer, you can index it like an array.

my_arr.get()[0] returns a reference to the first element in your 'array' of arrays.

You can then use std::array's indexing operator to get an element.

my_arr.get()[0][0] returns a reference to the element you want.

Alternatively, you could write:

my_arr->at(0) my_arr->operator[](0) (*my_arr)[0] *my_arr->data() 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: