初始化程序列表*参数*评估顺序 [英] Initializer list *argument* evaluation order

查看:111
本文介绍了初始化程序列表*参数*评估顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,C ++标准要求类成员按照它们在类中声明的顺序来初始化,而不是在任何构造函数的初始化器列表中提及它们的顺序。然而,这并不意味着对这些初始化的参数进行求值的顺序。我正在使用一个系统,它经常传递对序列化对象的引用,并想知道我是否可以确保从正确的顺序读取它的位,独立于这些位写入对象的字段的顺序。 p>

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 code> 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 ++标准 12.6.2 / 3


每个基础和成员初始化后都有一个序列点(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.

一个mem初始化程序的表达式列表被作为初始化相应基础或成员的一部分来计算。初始化是你在问题中指定的。评估是此初始化的一部分,初始化不能交错(因为它们之间有一个序列点)。

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.

这篇关于初始化程序列表*参数*评估顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆