c++ - 委托(delegate)执行者是否受参数评估顺序的影响?

标签 c++

最多 Order of evaluation in C++ function parametersWhat are the evaluation order guarantees introduced by C++17?委托(delegate)人是否受评估顺序影响?

struct A
{
    A( int a, int b ) : mA(a), mB(b) {}
    A( std::vector<u8>::const_iterator& aBuffer ) :
        A( CreateIntFromBuffer(aBuffer), CreateIntFromBuffer(aBuffer) ) {}
};

我需要再次使用 mAmB 名称自述吗?

c++XX 标准有区别吗?

最佳答案

[class.base.init]

7 The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of [dcl.init] for direct-initialization.

[dcl.init]

19 If the initializer is a parenthesized expression-list, the expressions are evaluated in the order specified for function calls.

鉴于以上两段,我会得出结论,评估的顺序是......

A( CreateIntFromBuffer(aBuffer), CreateIntFromBuffer(aBuffer) )

... 两个调用中的一个未指定(除了不交错)。因此,您不能依赖左侧调用在右侧调用之前完成,反之亦然。

可以通过使用大括号初始化列表来强制从左到右的评估顺序,例如...

A{ CreateIntFromBuffer(aBuffer), CreateIntFromBuffer(aBuffer) }

...但我认为它至少是大括号初始化的一种神秘用法。考虑重构。

在紧要关头,可以使用返回 A 的命名函数,并委托(delegate)给复制/移动构造函数:

struct A
{
    static A makeA(std::vector<u8>::const_iterator& aBuffer) {
        int a = CreateIntFromBuffer(aBuffer);
        int b = CreateIntFromBuffer(aBuffer);
        return A(a,b);
    }
    A( int a, int b ) : mA(a), mB(b) {}
    A( std::vector<u8>::const_iterator& aBuffer ) : A(makeA(aBuffer)) {}
};

由于有保证的复制省略,这实际上不会涉及任何拷贝。

关于c++ - 委托(delegate)执行者是否受参数评估顺序的影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58268616/

相关文章:

C++ ctors : What's the point of using initializer list in a . cpp 文件?

c++ - C++ 中的嵌套命名空间

c++ - 我的程序不断抛出编译错误,我无法弄清楚错误发生的原因

c++ - C++ 容器上的通用操作

c++ - 使用 cpprest 通过 json 对象在 http post 中发送图像

c++ - stringstream operator>> 停止问题

C++使用数组设置交集和并集

c++ - 析构函数和映射

c++ - 在 Linux 上运行应用程序时要观察的参数?

c++ - 如何检查特定文件夹中是否存在任何文件?