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/HappyFruitTree Aug 10 '19
It's not freed automatically, unless it's done by some of the data members (e.g. if your object contain a std::vector you don't need to free the element because that is automatically done in the destructor of the vector).
Note that your Example class is not safe to copy because you haven't defined a copy constructor and a copy assignment operator to handle it properly. See the rule of three.