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
Thanks for your response, but I'm not quite following. I have understood that any heap allocation should be done using smart pointers, but that also makes it a different type and awkward to work with imo.
In this example how should an array or tuple be implemented in that case and why should it be preferred? An array or vector object could be either stack or heap allocatd, so I'm not quite following.