开发者

Member fields, order of construction

In C++, when doing something like what you see below, is the order of construction guar开发者_JAVA百科anteed?

Logger::Logger()
    : kFilePath_("../logs/runtime.log"), logFile_(kFilePath_)
{
    // ...
}


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.


The order of construction is the order of declaration in the class definition.

If the ordering in the ctor-initializer differs, this does not affect the order of construction. Your compiler may warn on this.

See 12.6.2/5 (2003 wording, named [class.base.init]):

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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜