First I want to say that, I have a vector which has thousand of vectors inside. Each of these inside vectors has thousand of numbers inside. I want to keep memory management safe and memory usage at minimum as much as possible.
I want to ask that if I have a code similiar to below
int size = 10;
vector<vector<double>>* something = new vector<vector<double>>(size);
vector<double>* insideOfSomething;
for(int i = 0; i < size; i++){
insideOfSomething = &(something->at(i));
//...
//do something with insideOfSomething
//...
}
I know that ‘something’ will be created in heap. What I don’t understand is where the vectors are placed, ‘insideOfSomething’ points? If they are created in stack, then this means that I have a vector pointer, which points a vector in heap, that has vectors inside which are created in stack? (I’m very confused right now.)
If I have a code similiar to the one below;
vector<vector<double>*>* something = new vector<vector<double>*>(size);
vector<double>* insideOfSomething;
for(int i = 0; i < size; i++){
something->at(i) = new vector<double>();
insideOfSomething = something->at(i);
//...
//do something with inside insideOfSomething
//...
}
right know all of my vectors are stored in heap, right?
Which one is more usefull according to the memory management?
Let’s take a random, simplistic implementation of vector, as I think this will help you.
In this case, if we write:
… the pointer,
buffer, the integrals:vector_sizeandvector_capacity, and the allocator object,alloc, will all be created on the stack (along with allocating any additional memory necessary for structure padding and alignment).However, vector itself will allocate memory on the heap to which this
bufferpointer will store its base address. That will always be on the heap and will contain the actual contents of the vector as we think of them.This is still more efficient than this:
… as this would involve a heap allocation/deallocation for the vector itself (including its data members) in addition to the memory vector itself allocates for its internal contents (the buffer). It also introduces an additional level of indirection.
Now if we have a vector of
Somethings(vector of vector or anything else):Those
Somethinginstances are always going to be allocated within a contiguous heap buffer since they would reside in the dynamically allocated memory blocks that vector creates and destroys internally.