C++ With Initializer List a thing, when to use normal constructor?

后端 未结 3 839
無奈伤痛
無奈伤痛 2021-01-06 18:50

I just started getting back into C++ here recently and learned about Initializer Lists. It seems to be the standard way to initialize members. That being said I have 2 quest

3条回答
  •  無奈伤痛
    2021-01-06 19:25

    The constructor initializer list is a very useful tool. I would reject your code in code review if you wouldn't be using it.

    C++ has 2 ways of initializing members. Whenever you declare your member, you can give it a default value:

    class C {
        int i = 42;
    public:
        C(int j);
        C() = default;
    };
    

    This is a very useful technique to initialize simple members on a good default value.

    Than, you have the initializer list:

    C(int j) : i{j} {}
    

    In this list, you can override the initialization. All members not mentioned get the initialization from the definition. Note that classes with default constructors don't require explicit initialization.

    The initializer list can use the arguments of the constructor. However by initializing the members on definition, it is easier to spot uninitialized members.

    So when not to use the initializer list for initialization? Never, as assignment in the constructor body is assignment, not initialization.

    You never really need the body to assign members, however, if you don't have the -Wreorder warning active, it might make sense to assign a member that depends on another.

提交回复
热议问题