C++ - initializing variables in header vs with constructor

前端 未结 7 925
盖世英雄少女心
盖世英雄少女心 2021-01-31 02:00

Regarding the following, are there any reasons to do one over the other or are they roughly equivalent?

class Something
{
    int m_a = 0;
};

v

7条回答
  •  旧巷少年郎
    2021-01-31 02:28

    If you change the code like what Christian did to make them do the same thing. Now it is a tradeoff between compile-time optimization (which Christian explained completely) and run-time optimization.

    class Foo{
    
    public: 
     Vector vec1;
     .
     .
     .
      Vector vecN;
    }
    

    Imagine you have to initialize each vector by some predefined doubles. If the program must instantiate many and many objects of this class, it is better to initialize the vectors in the header file to make the user happy by reducing the run-time!

提交回复
热议问题