1

Say I do something like this

for(int i = 0; i < 10; i++)
{
    //create a pointer object using new
    //use the object
}

Do I need to delete the pointer object after using it in the loop? I was thinking like, if I didn't delete it, it will keep creating a new object for 10 times and the object just hang in there after that, eating resources.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Darren
  • 61
  • 2
  • 5

5 Answers5

5

Yes, for every new there needs to be a corresponding delete. (And a delete[] for every new[].)

However, the C++ way would be to avoid dynamic storage as much as possible and rather employ local, automatic variables:

for(int i = 0; i < 10; ++i)
{
    some_class object;
    //use object
} // object gets destroyed here automatically 

If you need to allocate that object dynamically (which I doubt, but there are such cases), then use a smart pointer. A smart pointer will execute the delete for you, no matter which way you leave the scope it belongs to:

for(int i = 0; i < 10; ++i)
{
    smart_ptr<some_class> object(new some_class());
    //use object
} // object gets destroyed here automatically 

The current standard only knows one smart pointer, named std::auto_ptr, which would would do what you need in this case. The next standard will come with several more, among them a replacement for std::auto_ptr, named std::unique_ptr, and one with shared ownership semantic, named std::shared_ptr. Your compiler/std lib might actually already support them. If not, you can find them among the many great libraries to be found at boost.


BTW, note that I have replaced your i++ with ++i. In case of an int this doesn't make any difference in your scenario, but there are types for which i++ might create an unnecessary copy. (If efficiency wouldn't concern you, why program in C++?)

sbi
  • 219,715
  • 46
  • 258
  • 445
4

Yep.

You must delete something that you new'ed when you no longer need it, otherwise you'll get a memory leak.

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
1

Yes technically you need to delete them.

But. We have this amazing thing called smart pointers that do this auto-magically.

for(int i = 0; i < 10; i++)
{
    std::auto_ptr<int> x(new int(10));

    // automatically deleted after each iteration.
}
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
Martin York
  • 257,169
  • 86
  • 333
  • 562
0

If you were so inclined you could use a smart pointer (something like Boost's shared_pointer) and then as soon as the pointer went out of scope for the final time the object would automatically be deleted.

Chris Pfohl
  • 18,220
  • 9
  • 68
  • 111
0

Yes, you need to delete it. But doing a new/delete every iteration of the loop may not be the best option -- you need to provide more context to get better advice.

Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80