0

I am having a hard time finding the answer to the following:

What is the best practice way of allocating a 2d array of ints that is contiguous in memory on the heap in c++14.

Conditions:

  • The width and height is known at compile time but I would still like to put the 2d array on the heap for various reasons.
  • I would like to access memory locations using the 2d syntax arr[x][y]
  • I do not want to implement my own wrapper if possible

Sub questions:

  • Do I have to use std::array or is the native int[][dim] syntax usable?
  • Is it possible to have a unique_ptr to the 2d array?

Thanks in advance for answers.

Mike Kinghan
  • 51,203
  • 11
  • 140
  • 171
rSir
  • 73
  • 4

1 Answers1

3

You could use a unique_ptr that holds a raw array:

std::unique_ptr<int[][Y]> p(new int[X][Y]);

However, this doesn't give you meaningful bounds checking on the first axis, nor does it let you iterate using range-based for.


You could use a unique_ptr that holds a std::array

std::unique_ptr<std::array<std::array<int, Y>, X>> p;

However, this doesn't let you index, since operator[] is only defined for raw arrays.


I would just write my own wrapper that gives me the best of both. Something like:

template <typename T, size_t X, size_t Y>
struct Array {
    Array() {
        p.reset(new T[X][Y]);
    }   

    using row = T[Y];

    row* begin() { return p.get(); }
    row* end() { return p.get() + X; }

    row& operator[](size_t y) { return p[y]; }

    std::unique_ptr<int[][Y]> p;
};
Barry
  • 267,863
  • 28
  • 545
  • 906
  • 3
    Note that data in nested `std::array`'s are _not_ guaranteed to be contiguous (https://stackoverflow.com/q/9762662/873025). – Felix Glas Nov 01 '17 at 16:58