Preety Preety - 1 month ago 11
C++ Question

Deleting objects in C++ explicitly

I have a class

myclass
.
In the main function, I create objects of type
myclass
in every iteration and want to delete them after each iteration. I have not created the objects dynamically. Can I delete the them explicitly because I don't need them after the iteration gets over.

class myclass{
int value;
void do_function();
};

int main()
{
for(int i=0;i<count;i++)
{
myclass obj;
obj.do_function();
}
}


The object
obj
is not needed after one iteration, but the memory is still there. How can I free that memory?

Answer

You don't have to delete them explicitly, because as you have created them myclass obj; they are created on stack and deleted after each iteration.

When the program reaches the first curly brace after the instantiation on stack of an object it deletes it, in your case:

myclass obj;
obj.do_function();
} // Here the obj is deleted

Here are some examples and explanations of how stack is working, versus heap, to let you understand better when you need to free memory yourself, and when you don't.

Note: I have used notions of stack and heap only to suggest how objects are handled relatively to their lifetime like when an object from stack should be freed after it leaves the scope, and an object of heap lives util it's explicitly freed. As mentioned in comments, these notions are not considered in standard C++ because the programs can run in an environement which does not support these type of memory. Although the copiler respects these rules for a C++ program.

Comments