qeia qeia - 3 months ago 21
C++ Question

use std::vector for dynamically allocated 2d array?

So I am writing a class, which has 1d-arrays and 2d-array, that I dynamically allocate in the constructor

class Foo{
int** 2darray;
int * 1darray;
};

Foo::Foo(num1, num2){

2darray = new int*[num1];
for(int i = 0; i < num1; i++)
{
array[i] = new int[num2];
}
1darray = new int[num1];
}


Then I will have to delete every 1d-array and every array in the 2d array in the destructor, right?
I want to use std::vector for not having to do this. Is there any downside of doing this? (makes compilation slower etc?)

TL;DR: when to use std::vector for dynamically allocated arrays, which do NOT need to be resized during runtime?

Answer

vector is fine for the vast majority of uses. Hand-tuned scenarios should first attempt to tune the allocator1, and only then modify the container. Correctness of memory management (and your program in general) is worth much, much more than any compilation time gains.

In other words, vector should be your starting point, and until you find it unsatisfactory, you shouldn't care about anything else.

As an additional improvement, consider using a 1-dimensional vector as a backend storage and only provide 2-dimensional indexed view. This scenario can improve the cache locality and overall performance, while also making some operations like copying of the whole structure much easier.


1 the second of two template parameters that vector accepts, which defaults to a standard allocator for a given type.