初始化器列表 *argument* 评估顺序

因此,C++ 标准要求类成员按照它们在类中声明的顺序进行初始化,而不是按照它们在任何构造函数的初始化列表中的顺序进行初始化.但是,这并不意味着评估这些初始化的参数的顺序.我正在使用一个经常传递对序列化对象的引用的系统,并且想知道我是否可以确保以正确的顺序从中读取位,而与这些位写入对象字段的顺序无关.

So, the C++ standard requires that class members be initialized in the order in which they are declared in the class, rather than the order that they're mentioned in any constructor's initializer list. However, this doesn't imply anything about the order in which the arguments to those initializations are evaluated. I'm working with a system that frequently passes references to serialization objects around, and wondering if I can ensure that bits are read from it in the right order, independent of the order in which those bits get written into the object's fields.

struct Foo {
    int a;
    double b;
    // I want to be able to do this
    Foo(SerObj &s)
    : b(s.readDouble()), a(s.readInt())
    { }
    // Rather than this
    Foo (SerObj &s)
    {
        b = s.readDouble();
        a = s.readInt();
    }
};

显然,在声明中重新排序诸如 intsdoubles 之类的东西并不是什么大不了的事,但有时更大的对象和需要动态分配的东西就可以了.

Obviously, reordering things like ints and doubles in the declaration is not too big a deal, but bigger objects and things requiring dynamic allocation sometimes can be.

推荐答案

C++标准12.6.2/3:

每个基和成员初始化后都有一个序列点(1.9).mem-initializer 的表达式列表作为相应基类或成员初始化的一部分进行评估.

There is a sequence point (1.9) after the initialization of each base and member. The expression-list of a mem-initializer is evaluated as part of the initialization of the corresponding base or member.

初始化的顺序是您在问题中指定的顺序.评估是这个初始化的一部分,初始化不能交错(因为它们之间有一个序列点).

The order of the initialization is the one you specified in the question. Evaluation is part of this initialization, and the initializations can't interleave (because there is a sequence point between them).

这意味着初始化器列表中的函数调用不是按所需顺序调用的,而是按成员声明出现的顺序调用的.

That means that the function calls in your initializer lists are not called in the desired order, but in the order in which the member declarations appear.

相关文章