Is the order of initialization guaranteed by the standard?

后端 未结 5 496
情书的邮戳
情书的邮戳 2020-12-31 12:44

In the following code snippet d1\'s initializer is passed d2 which has not been constructed yet (correct?), so is the d.j in D\'s copy constructor an uninitialized memory ac

5条回答
  •  爱一瞬间的悲伤
    2020-12-31 12:56

    In your example it will fail:

    struct A
    {
        D d1, d2;    
        A() : d2(2), d1(d2) {}
    };
    
    d1: is initialised first as it is declared first.
    d2: is then initialized.
    

    As a result the initializer list will construct d1 using a reference to an invalid object (d2).

    This is one reason to turn up your compilers warning level as high as possable.
    And additionaly force it to report all warnings as errors.

提交回复
热议问题