因此,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();
}
};
显然,在声明中对 ints
和 doubles
之类的东西重新排序并不是什么大不了的事,但有时需要动态分配的更大的对象和东西可能会.
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++ Standard 12.6.2/3
:
C++ Standard 12.6.2/3
:
每个base和member初始化后都有一个序列点(1.9).内存初始化器的表达式列表作为相应基类或成员初始化的一部分进行评估.
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.
这篇关于初始化列表*参数*评估顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!