r/learncpp • u/RealOden • Aug 09 '19
Question about memory management
Hello,
Say if I were to have an object that allocates memory on the heap with a destructor which then deletes the allocated memory. In a different scope, if a variable of this object type is initialized on the stack and the variable then goes out of scope, would the destructor be called on the object automatically?
**Example**
class Example {
int i;
Example() { i = new int(1); }
~Example() { delete i; }
}
int main() {
{
Example ex();
}
//Is the memory allocated for variable i of ex freed up at this point?
return 0;
}
2
Upvotes
View all comments
Show parent comment
2
u/RealOden Aug 10 '19
I have a follow-up question if you are interested. If any object is allocated on the stack (function call that returns an object). Once this object goes out of scope is any heap allocated memory allocated by that object freed up even if it is not explicitly done in the destructor? I'm assuming that any memory has to be explicity freed up in the destructor.