Keep in mind that regardless of where the object itself is created, the object or one of its members may internally use heap memory.
Can you please explain this?
Also if the object is created on stack why do we need destructor? In the main(), objects would behave as automatic variable and get destroyed automatically right before the scope of main ends. In the same manner as for any other function.
E.g.
Code:
void f()
{
double d;
}
The object d gets destroyed automatically when the scope of function is over.
Also if the object is created on stack why do we need destructor? In the main(), objects would behave as automatic variable and get destroyed automatically right before the scope of main ends. In the same manner as for any other function.
E.g.
Code:
void f()
{
double d;
}
The object d gets destroyed automatically when the scope of function is over.
The destructor is for the object to clean up any memory it may have used. In your simple example, you don't need one, but if the object contained a pointer to something it had allocated on the heap, it would need to delete that memory, and the destructor is the best place to do that.
The object getting deleted when it goes out of scope has nothing to do with whether you need a destructor or not. As Lindley said, the object itself may reside on the stack, but that doesn't mean it isn't allocating stuff on the heap.
Your choices are heap or stack. Since it's not heap...
You're forgetting global data. Which is neither on the heap nor the stack.
It's in the .data or .rdata segment. (note that it can be in rdata safely if it has only const data, but does have a constructor/destructor).
Consider a std::vector<int>. The vector object itself is always the same size (which you can check with sizeof()), but it can hold variable numbers of elements in its array. Clearly, then, the array is not directly inside the object. Instead, the vector holds an internal pointer to heap memory where the array is managed.
Bookmarks