最多 Order of evaluation in C++ function parameters和 What 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) ) {}
};
我需要再次使用 mA
和 mB
名称自述吗?
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/