C++ Initialising fields directly vs initialisation list in default constructor

前端 未结 3 1372
执笔经年
执笔经年 2021-01-03 20:16

I\'d like to know if there is a difference between this code:

class Foo{
 private:
    int a = 0;
 public:
    Foo(){}
}

And:



        
3条回答
  •  臣服心动
    2021-01-03 21:12

    The two are identical.

    One rule of software engineering is DRY -- don't repeat yourself. DRY states that if you can avoid repeating the same token twice, or having two identical lists, you should.

    This is for a few reasons. Maintaining two identical lists is surprisingly error prone; one gets modified, or has a typo, and the other does not. It makes code longer, which can make it harder to read. And avoiding copy-paste coding encourages using some very powerful and expressive techniques that can make what you are doing clearer than doing it manually 17 times.

    struct foo {
      int a;
      foo():a(7) {}
    };
    

    here we have repeated ourselves -- the list of member variables, in particular, is listed twice. Once in the definition of foo, and again in the initializer list of foo::foo. If it is missing somewhere, you get uninitialized data.

    struct foo {
      int a = 7;
      foo() {}
    };
    

    Here we do not repeat ourselves.

    struct foo {
      int a = 7;
      foo() {}
      foo(int i):a(i) {}
    };
    

    Here there is some repetition, but the repetition is unavoidable. It is, however, minimized.

    There is some cost here, because someone might interpret a=7 to mean "it always starts at 7", and not "the default is 7".

    struct foo {
      int a = 7;
      foo():a(3) {}
      foo(int i):a(i) {}
    };
    

    And the above is a horrible anti-pattern.

提交回复
热议问题