Member fields, order of construction

前端 未结 2 1395
[愿得一人]
[愿得一人] 2020-11-30 10:49

In C++, when doing something like what you see below, is the order of construction guaranteed?

Logger::Logger()
    : kFilePath_(\"../logs/runtime.log\"), lo         


        
2条回答
  •  暖寄归人
    2020-11-30 11:28

    Yes, the order of construction is always guaranteed. It is not, however, guaranteed to be the same as the order in which the objects appear in the initializer list.

    Member variables are constructed in the order in which they are declared in the body of the class. For example:

    struct A { };
    struct B { };
    
    struct S {
        A a;
        B b;
    
        S() : b(), a() { }
    };
    

    a is constructed first, then b. The order in which member variables appear in the initializer list is irrelevant.

提交回复
热议问题