Has the new C++11 member initialization feature at declaration made initialization lists obsolete?

前端 未结 3 746
遥遥无期
遥遥无期 2020-11-29 18:11

With C++11, we now have the ability to initialize class members in a header declaration:

class aClass
{
    private:
        int mInt{100};
    public:
              


        
3条回答
  •  感动是毒
    2020-11-29 18:49

    The way I look at it, in-class initialization is an ehancement of mem-initializer-lists. In C++03, members not listed in a mem-initializer-list were always default initialised. This means the default constructor for classes, and no initialization for primitive types.

    In-class initialization simply allows you to specify your own defaults. There are two ways to look at it.

    One: if most/all constructors of your class want to provide the same initial value for a member, use an in-class initializer for that member. For other members, use mem-initializer-lists. You'll of course have to use those whenever the initial value depends on constructor arguments.

    The other one: provide an in-class initializer for all members, exactly how the default constructor of your class would initialise them. Then, mem-initializer-lists in non-default constructors get the semantics of "how it differs from a default-constructed object."

提交回复
热议问题