PDA

View Full Version : Basic question about allocation



feraudyh
23rd June 2010, 19:15
Suppose I have a function in the code of which I have
QVector<int> myvector;
further down I append elements to myvector
like this

myvector.append(3)
Where does the allocation take place? On the stack? On the heap?
What do I need to know about freeing the memory?

Zlatomir
23rd June 2010, 19:20
The QVector object is on the stack (where you allocated memory for it) but he <most likely> allocates memory on the heap for the elements (and take care to release it), if you need to know more you can open the source code and see exactly how this works.

The QVector will take care of the memory, you don't need to worry, it will not leak.

SneakyPeterson
24th June 2010, 09:44
Suppose I have a function in the code of which I have
QVector<int> myvector;
further down I append elements to myvector
like this

myvector.append(3)
Where does the allocation take place? On the stack? On the heap?
What do I need to know about freeing the memory?

I believe that allocation for both will take place on the heap. For variables where you do not specifically allocate memory with
the "new" operator, temporary space is allocated for them on the stack. This means that all allocation and deletion will be handled
for you, but it also limits the scope of those variables to that function on the stack where they are defined. Hence, every time you
jump to a different part of the stack (usually through a different function call) if you can only send through values as parameters, not
variables that can be modified. This method of scope and how memory allocation works is perhaps the most important thing to understand
about c, and one of the more important things to understand in c++.

SneakyPeterson
24th June 2010, 09:46
Just for clarification: when I said "both" i mean the "QVector" and the "int" with a value of 3 that you place into the vector.

Zlatomir
24th June 2010, 10:13
@SneakyPeterson: The QVector object is allocated on the stack and it has some pointers to typename T, witch (the pointer itself) it's also on stack, but it is used to allocate memory on the heap.

If the vector itself will be on the heap, how it will be auto-deleted? It can't, it doesn't have the "parenting thing" (only the GUI parts on Qt have that).

SneakyPeterson
24th June 2010, 13:42
I wasn't aware that QVector worked that way with primitives... Ah well.

http://blogs.pitch.com/plog/the_more_you_know2.jpg