My question is, "What happens if we create objects within a loop?"
Example:
for (int i = 0; i < iterations; i++)
{
Foo* bar = new Foo(i); //here Foo(i) is a parameterized constructor
}
and how to delete them?
The way you wrote, you are creating a new object on the free store (the heap) at every iteration. You may want either to destroy the object at the end of the loop:
for (int i = 0; i < iterations; i++)
{
Foo* bar = new Foo(i); //here Foo(i) is a parameterized constructor
// do stuff...
delete bar;
}
or collect pointers in a container and destroy it later:
std::vector<Foo*> v;
for (int i = 0; i < iterations; i++)
{
Foo* bar = new Foo(i); //here Foo(i) is a parameterized constructor
v.push_back(bar);
}
// do stuff...
for(size_t i = 0; i < v.size(); ++i)
{
delete v[i];
}
Memory leaks.
First iteration a bar
object will be created and allocated the memory its needed. The next iteration (and all) the previous reference of bar
will be lost and a new memory reference will be allocated. So you can not find the previously created bar
.
As all of the previous reference of bar
is lost, you cannot delete
or free
those memory and hence, Memory Leak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With