Dependencies in Initialization Lists

前端 未结 3 1383
别跟我提以往
别跟我提以往 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条回答
  •  庸人自扰
    2021-02-12 15:05

    No, initialization order is defined by the declaration order in the class itself.

    From the C++ standard 12.6.2 [class.base.init] p5:

    Initialization shall proceed in the following order:
    — First, and only for the constructor of the most derived class as described below, virtual base classes shall be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base class names in the derived class base-specifier-list.
    — Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
    — Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
    — Finally, the body of the constructor is executed.
    [Note: the declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. ]

提交回复
热议问题