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();
}
};
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…