函数参数的销毁顺序是什么?
What is the order of destruction of function parameters?
这是我之前问题 的后续问题,因为我不小心混淆了参数和参数。感谢 Columbo 和 T.C。清除我在该问题的评论中的术语混淆。
如果某些函数的主体 f
的参数 p_1
、...、p_n
类型为 T_1
、...、T_n
分别抛出异常,完成或returns,参数销毁的顺序是什么,为什么?如果可能,请提供对标准的引用。
示例:
template <typename ... Args>
void f(Args ... params) {} // in what order are params destroyed?
void f(T1 p1, T2 p2, T3 p3) {} // in what order are p1, p2 and p3 destroyed?
参数销毁的确切时间点是unspecified:
CWG decided to make it unspecified whether parameter objects are destroyed immediately following the call or at the end of the full-expression to which the call belongs.
构造参数的顺序也是未指定的,但是由于函数参数具有块作用域,虽然它们的构造顺序未指定,析构是构造的相反顺序.例如。考虑
#include <iostream>
struct A {
int i;
A(int i) : i(i) {std::cout << i;}
~A() {std::cout << '~' << i;}
};
void f(A, A) {}
int main() {
(f(0, 1), std::cout << "#");
}
打印 10#~0~1
with GCC and 01#~1~0
with Clang; they construct parameters in different orders, but both destroy in the reverse order of construction, at the end of the full-expression the call occurs in (rather than right after returning to the caller). VC++ prints 10~0~1#
.
这是我之前问题
如果某些函数的主体 f
的参数 p_1
、...、p_n
类型为 T_1
、...、T_n
分别抛出异常,完成或returns,参数销毁的顺序是什么,为什么?如果可能,请提供对标准的引用。
示例:
template <typename ... Args>
void f(Args ... params) {} // in what order are params destroyed?
void f(T1 p1, T2 p2, T3 p3) {} // in what order are p1, p2 and p3 destroyed?
参数销毁的确切时间点是unspecified:
CWG decided to make it unspecified whether parameter objects are destroyed immediately following the call or at the end of the full-expression to which the call belongs.
构造参数的顺序也是未指定的,但是由于函数参数具有块作用域,虽然它们的构造顺序未指定,析构是构造的相反顺序.例如。考虑
#include <iostream>
struct A {
int i;
A(int i) : i(i) {std::cout << i;}
~A() {std::cout << '~' << i;}
};
void f(A, A) {}
int main() {
(f(0, 1), std::cout << "#");
}
打印 10#~0~1
with GCC and 01#~1~0
with Clang; they construct parameters in different orders, but both destroy in the reverse order of construction, at the end of the full-expression the call occurs in (rather than right after returning to the caller). VC++ prints 10~0~1#
.