Hi there!
I'm not new to programming, but kind of new to C++. One of my biggest concerns, and probably most C++ devs major concern, is memory management. I'll try to make my actual problem as clear as possible. Here's what I suspect to know for sure:
a) Local variables are allocated on the stack and deallocated after the end of a block and/or a function or special statement.
b) Dynamic memory allocated on the heap has unlimited lifetime until deallocated manually.
Ok. Still, what happens to objects and primitive data if used like this (completely hypothetical code, but exactly depicting what I mean):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include "Object.h"
#include "TypeT.h"
void insert(Object &obj);
int main(int argc, char* argv[]{
// suppose we're looking at an object allocated automatically.
// the object contains an internal vector of a TypeT.
Object obj;
// now let's call the function "insert" and add some other
// object to obj's internal vector
insert(obj);
// now use some print method putting some value in TypeT out
// on the standard output stream.
obj.print();
return 0;
}
void insert(Object &obj){
TypeT t_obj;
obj.addElement(t_obj);
}
//suppose this is addElement's declaration/definition
void Object::addElement(TypeT &e){
data.push_back(e); //where data is "private vector<TypeT> data";
}
|
I hope the code is understandable. Shouldn't the object
t_obj be destroyed when
insert() returns and shouldn't the referenced address
stored in the vector through the above calls be invalid then? Obviously this isn't the case since the
print() will put out the values correctly. But how does C++ know which variables to deallocate and which ones to keep in such cases?
Simply put: I don't exactly know what happens to locally defined types referenced by types defined in a higher level bock. Does something like the general rule for objects in Java apply (as long as an object is somehow referenced it won't not garbage collected)?
Hopefully my question isn't too confusing.
Thank you in advance for your help!
Thomas