There is nothing bad about the new keyword, it's always at the bottom of dynamic space allocation, even when you use std::vector<>
and friends. std::unique_ptr
and such have their issues as well. But this is not, what my answer is about.
My answer is about the cases, where you need to avoid new
for performance reasons (it is a very costly operator, taking a few hundred cycles).
You can usually avoid allocating your array line by line, by simply allocating it all in one go, and building the pointer structure you need manually:
size_t fieldSize = width*height*sizeof(int);
size_t pointerArraySize = height*sizeof(int*);
char* memory = new char[fieldSize + pointerArraySize];
int** pointerArray = (int**)memory;
int* dataArray = (int*)&memory[pointerArraySize];
for(long i = height; i--; ) pointerArray[i] = &dataArray[i*width];
Ok, this is a little more hassle than doing many individual allocations, but quite a bit faster. And, as a bonus, deallocation is a one-liner:
delete[] (char*)pointerArray;