views:

174

answers:

2

Hello,

What is the best way in C++ to use std::map in loops ?

  • dynamically allocated
  • stack allocated

Code:

for(int i=0;i<3;i++)
{
  std::map<int,int>* m = new std::map<int,int>;
  //or ...
  std::map<int,int> m;

}
+7  A: 

That is not a static instance; a static instance would use the static keyword (and you wouldn't be creating a new one each time through the loop).

That is a local variable.

In C++, you should always prefer to use local variables over dynamic allocation wherever possible. If you dynamically allocate an object (using new), then you have to remember to delete it when you are done with it and you have to jump through a lot of hoops to ensure exception safety.

James McNellis
It also helps avoid heap fragmentation
Michael Mrozek
@Michael: In many cases, yes, but in this case, all the nodes in the map are going to be allocated dynamically anyway, so there won't be much of a difference.
James McNellis
+6  A: 

Avoid new unless you really need it, i.e. the variable/structure has a lifetime unrelated to any calling scope. (If it "belongs" to the calling function, return by value.)

This is clearly not such a case. The second, preferable, example is called a local variable.

I would be making a choice between

for(int i=0;i<3;i++)
{
  std::map<int,int> m;
  …
}

and

std::map<int,int> m;
for(int i=0;i<3;i++)
{
  …
  m.clear();
}

The latter may perform better when the container is std::vector by reusing allocated memory. With map the difference is only style.

Potatoswatter