gpt4 book ai didi

c++ - 花括号和圆括号之间的参数评估顺序

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:12:40 26 4
gpt4 key购买 nike

#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>

uint32_t func() { return rand() % 10; }

struct A {
uint32_t _x, _y, _z;
A(uint32_t x, uint32_t y, uint32_t z) : _x(x), _y(y), _z(z) {}
};

int main() {
A a{func(), func(), func()};
//A a(func(), func(), func());

printf("%d %d %d\n", a._x, a._y, a._z);
return 0;
}

GCC 9.1MSVC 19.22.27905 在使用花括号或圆括号时都会打印不同的顺序。Clang 8.0.0 将为这两种情况打印相同的顺序。

我在标准中找不到关于它的任何内容,它是在标准中还是由编译器决定,它命令它计算输入参数?

最佳答案

只保证 braced-init-list 的顺序,[dcl.init.list]/4 :

(强调我的)

Within the initializer-list of a braced-init-list, the initializer-clauses, including any that result from pack expansions ([temp.variadic]), are evaluated in the order in which they appear. That is, every value computation and side effect associated with a given initializer-clause is sequenced before every value computation and side effect associated with any initializer-clause that follows it in the comma-separated list of the initializer-list. [ Note: This evaluation ordering holds regardless of the semantics of the initialization; for example, it applies when the elements of the initializer-list are interpreted as arguments of a constructor call, even though ordinarily there are no sequencing constraints on the arguments of a call. — end note ]

另一方面,order of evaluation of arguments in a function callunspecified .

unspecified behavior - the behavior of the program varies between implementations and the conforming implementation is not required to document the effects of each behavior. For example, order of evaluation, whether identical string literals are distinct, the amount of array allocation overhead, etc. Each unspecified behavior results in one of a set of valid results.

关于c++ - 花括号和圆括号之间的参数评估顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57442381/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com