What's the differences between member initializer list and default member initializer on non-static data member?

前端 未结 5 771
醉话见心
醉话见心 2020-12-28 18:13

I\'d like to understand what\'s the differences of using one form rather than the other (if any).

Code 1 (init directly on variables):

#include 

        
5条回答
  •  -上瘾入骨i
    2020-12-28 19:05

    In the C++ Core Guidelines (see note 1 below), Guideline C.48 recommends the first approach (in-class initializers.) The reasoning provided is:

    Makes it explicit that the same value is expected to be used in all constructors. Avoids repetition. Avoids maintenance problems. It leads to the shortest and most efficient code.

    In fact if your constructor does nothing but initialize member variables, as in your question, then Guideline C.45 is firmer still, saying to use in-class initializers for sure. It explains that

    Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.

    I am not going to argue with Stroustrup, Sutter, and several hundred of their friends and colleagues even if I haven't written a compiler so I can't prove it's more efficient. Use in-class initializers wherever you can.

    1. If you're not familiar with the guidelines do follow the links to see sample code and more explanations.

提交回复
热议问题