如果某个函数 f
带有参数 p_1
, ..., p_n
类型为 T_1
, .. ., T_n
分别用参数 a_1
, ..., a_n
调用,其主体以什么顺序抛出异常、完成或返回论据被破坏了吗?为什么?如果可能,请提供对标准的引用。
编辑:我实际上想问一下函数“参数”,但作为 T.C.并且哥伦布设法消除了我的困惑,我将这个问题留给了论点并询问了a new separate question about the parameters .请参阅对此问题的评论以了解区别。
最佳答案
我没有设法在标准中找到答案,但我能够在 3 个最流行的 C++ 兼容编译器上对此进行测试。 R Sahu 的答案几乎解释了它是实现定义的。
§5.2.2/8: The evaluations of the postfix expression and of the arguments are all unsequenced relative to one another. All side effects of argument evaluations are sequenced before the function is entered.
Visual Studio C++ 编译器 (Windows) 和 gcc (Debian)
参数按照与声明相反的顺序构造并以相反的顺序销毁(因此按照声明的顺序销毁):
2
1
-1
-2
Clang (FreeBSD)
参数按其声明的顺序构造并以相反的顺序销毁:
1
2
-2
-1
所有编译器都被指示将源代码视为 C++11,我使用以下代码段来演示这种情况:
struct A
{
A(int) { std::cout << "1" << std::endl; }
~A() { std::cout << "-1" << std::endl; }
};
struct B
{
B(double) { std::cout << "2" << std::endl; }
~B() { std::cout << "-2" << std::endl; }
};
void f(A, B) { }
int main()
{
f(4, 5.);
}
关于c++ - 函数参数的破坏顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36992039/