Dependencies in Initialization Lists

前端 未结 3 1391
别跟我提以往
别跟我提以往 2021-02-12 14:23

Is this behavior well-defined?

class Foo
{
    int A, B;

    public:

    Foo(int Bar): B(Bar), A(B + 123)
    {
    }
};

int main()
{
    Foo MyFoo(0);
    re         


        
3条回答
  •  旧时难觅i
    2021-02-12 15:23

    No, it's undefined. A will be initialized first (it's first in the class definition), and it uses uninitialized B.

    Class members are initialized in the order they appear in the class definition, irrespective of their order in the initialization list. Indeed, it is bad practice to mismatch the member definition order with the initialization list order.

    If your instance of Foo happened to have static duration, like in Foo f(0); int main(){}, the behavior is well-defined. Objects with static duration are zero-initialized before any other initialization takes place; in that case, A and B will be 0 when the constructor is run. After that, though, the behavior is the same: first A then B, giving A a value of 123 and B a value of Bar (still ugly).

提交回复
热议问题