I'm adding objects to a vector in a function. The code looks like the following:
class MyObj
{
int a;
int b;
MyObj( int ai, int bi )
{
this->a = ai;
this->b = bi;
}
};
vector<MyObj> myVec;
void foo()
{
MyObj objInst( 10, 20 );
myVec.push_back( objInst );
}
I expect the objects are taking space from the stack and hence after return of the function their memory should be released. To my experience that's not the case i.e the objects in the container can be accessed outside the function with no problem so far. Can someone please enlighten me why that's the case? Do STL containers copy the data of the object passed to them and keep it somewhere int the heap or in the global memory?
Thanks a lot @Louen for the comments. Read this article and learned a lot. https://www.internalpointers.com/post/c-rvalue-references-and-move-semantics-beginners
Here's the breakdown of what happens.
Your vector myVec
being defined outside of a function body is a global variable.
This means it is created at the beginning of the program execution (before main()
is called) and destroyed at the end (when main()
returns).
In your foo()
functions you create an instance of your class MyObj
on the stack, then you add a copy of it to your global vector.
You can check that it is copied by monitoring the copy constructor of MyObj
, as shown here.
When foo()
ends the instance of MyObj
you created is destroyed, but the instance created from the copy lives on in the global vector. It is only destroyed when the global vector itself is destroyed, i.e. after the end of main()
.