Creating an object in the loop

后端 未结 7 548
夕颜
夕颜 2021-01-14 00:56
 std::vector C(4);
 for(int i = 0; i < 1000;++i)
  for(int j = 0; j < 2000; ++j)
  {   
   C[0] = 1.0;
   C[1] = 1.0;
   C[2] = 1.0;
   C[3] = 1.         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 01:17

    I was under the (perhaps false) impression that this would provide optimization opportunities for the compiler.

    This is probably true for built-in types such as int or double.

    The issue here is that you are using vector which needs to run the constructor on entering the loop body, and the destructor when leaving. Since both these methods are non-trivial the compiler cannot optimise these away, as your program would no longer be correct.

    As a counter-examample for this, imagine what such an optimisation would do if you used a file object instead of a vector.

提交回复
热议问题