What is better when creating a new variable in a loop in C ++

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

  • dynamically distributed
  • stack selected

the code:

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

}
+3
source share
2 answers

Avoid newif you really don't need it, i.e. the variable / structure has a lifetime unrelated to any call area. (If it "belongs" to the calling function, return its value.)

This is clearly not the case. The second preferred example is called a local variable.

I would choose 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();
}

, std::vector . map - .

+6

; static ( ).

.

++ , . ( new), , , , , .

+6

Source: https://habr.com/ru/post/1745042/


All Articles