I am (re-) learning C++ (again, after many years of Java and Python), but it seems I am not familiar with the concepts of heap and stack any more. I am reading threads like this one, which makes it quite clear: local variables in functions/methods live on the stack and will be destroyed when leaving that function/method. For objects that I need longer I would need to allocate memory on the heap.
Fine. But not I am reading a bit of C++ code and see the following (simplified):
struct MyStruct
{
int Integer;
bool Boolean;
}
// in header file
class MyClass
{
TArray<MyStruct> MyArray; // TArray is a custom dynamic array in the framework
void FillArray();
TArray<MyStruct> GetArray() { return MyArray; }
}
// in cpp file
void MyClass::FillArray()
{
for(int i = 0; i < 10; ++i)
{
MyStruct s; // These objects are created on the stack, right?
s.Integer = i;
s.Boolean = true;
MyArray.Add(s);
}
}
So there is a custom struct MyStruct
, and a class that has a container MyArray
. Then at some point I call MyClass->FillArray()
to initialize the array. In that method I create objects of MyStruct
on the stack (i.e. not via new
) and add them to the array. From my understanding these objects within the array should be destroyed as soon as the FillArray()
methods returns.
Now at some point later in code I call MyClass->GetArray()
. And to my surprise the array returned does indeed contain all the struct objects that have been created before.
Why are these struct objects still there, why have they not been destroyed as soon as the FillArray()
method returns?