Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if we create objects within a loop?

Tags:

c++

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?

like image 827
rittik Avatar asked Dec 19 '22 03:12

rittik


2 Answers

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];
}
like image 150
Paolo M Avatar answered Jan 02 '23 06:01

Paolo M


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.

like image 37
rakeb.mazharul Avatar answered Jan 02 '23 07:01

rakeb.mazharul