开发者

what is better when creating new variable in a loop in c++

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;

}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜