如果某些函数f带有参数p_1,...,p_n类型T_1,...,T_n分别用参数调用a_1,......,a_n并且它的正文抛出异常,则完成或返回,参数被破坏的顺序是什么?为什么?如果可能,请提供标准参考.
编辑:我实际上想询问函数"参数",但是由于TC和Columbo设法清除了我的困惑,我将这个问题留下来讨论参数并询问一个关于参数的新单独问题.有关区别,请参阅有关此问题的评论.
根据C++ 14 [expr.call]/4:
参数的生命周期在定义它的函数返回时结束.
这似乎意味着参数的析构函数必须在调用函数的代码继续使用函数的返回值之前运行.
但是,此代码显示不同:
#include <iostream>
struct G
{
G(int): moved(0) { std::cout << "G(int)\n"; }
G(G&&): moved(1) { std::cout << "G(G&&)\n"; }
~G() { std::cout << (moved ? "~G(G&&)\n" : "~G()\n"); }
int moved;
};
struct F
{
F(int) { std::cout << "F(int)\n"; }
~F() { std::cout << "~F()\n"; }
};
int func(G gparm)
{
std::cout << "---- In func.\n";
return 0;
}
int main()
{
F v { func(0) };
std::cout << "---- End of main.\n"; …Run Code Online (Sandbox Code Playgroud) 在将一些C++代码从Microsoft Visual Studio移植到gcc时,我遇到了一个奇怪的错误,我最终归结为:
#include <iostream>
using namespace std;
class Foo {
public:
int data;
Foo(int i) : data(i)
{
cout << "Foo constructed with " << i << endl;
}
Foo(const Foo& f) : data(f.data)
{
cout << "copy ctor " << endl;
}
Foo(const Foo&& f) : data(f.data)
{
cout << "move ctor" << endl;
}
~Foo()
{
cout << "Foo destructed with " << data << endl;
}
};
int Bar(Foo f)
{
cout << "f.data = " …Run Code Online (Sandbox Code Playgroud) 如果我有一个函数将对象Bar作为参数的设置,则将该对象传递给本地类Foo,并在其析构函数中Foo使用Bar如下:
class Foo {
public:
Foo(const Bar& bar) : bar_(bar) {}
~Foo() {
bar_.DoSomething();
}
private:
const Bar& bar_;
};
void example_fn(const Bar& input_bar) {
Foo local_foo(input_bar);
// ... do stuff.
// When foo goes out of scope, its destructor is called, using input_bar.
}
Run Code Online (Sandbox Code Playgroud)
如果example_fn用临时调用Bar input_bar,是否Foo local_foo保证局部变量在临时参数之前被销毁?换句话说,参数是否保证比局部变量更长?