Hi all,

I am doing something like this

int f(){
umap::iterator p = mmap.find(s);
           if(p != mmap.end()){
                  .......
           }
}

My memory usage is somehow constantly increasing.
While exiting the function do I need explicitly delete the iterator p?

Thanks in advance,

_alen

Re: unordered_map::iterator do I need to delete it explicitly? 80 80

Short Answer: No.

Long Answer...

You only need to delete something if
- You created the object using new (or you used some other library or function which created it with new)
- You own the object (i.e. it is not owned by a smart pointer or another class from another library)
- There are no other pointers anywhere in your program which are referring to the object


In the example you've given; assuming you're talking about deleting your iterator 'p' - it's an object with automatic storage duration - you haven't created it with new, therefore it will be cleared up as soon as it drops out of scope.

In fact, calling delete on it would be invalid (undefined behaviour) and could cause your program to malfunction or crash.


If you think you're getting memory leaks, have a look at anywhere that you're calling new with 'raw' pointers, then investigate whether there's anything you can do to reduce your usage of them (e.g. replacing raw pointers with std::shared_ptr)

e.g. - the following needs a delete because there's a raw pointer:

MyClass* bob = new MyClass;
delete bob;

but this uses a smart pointer which does the cleanup for you:

#include <memory>
std::shared_ptr<MyClass> bob( new MyClass );
// or..
auto fred = std::make_shared( new MyClass );
Re: unordered_map::iterator do I need to delete it explicitly? 80 80

Bench thanks!

Re: unordered_map::iterator do I need to delete it explicitly? 80 80

is problem solved?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.