假设我有以下代码:
int bar = 0;
struct Foo {
~Foo() { bar = 1; }
};
int main(int argc, char ** argv) {
Foo f;
return bar;
}
程序的返回值是多少? 0 还是 1?
最佳答案
来自 [stmt.return]/3:
The copy-initialization of the returned entity is sequenced before the destruction of temporaries at the end of the full-expression established by the operand of the return statement, which, in turn, is sequenced before the destruction of local variables (6.6) of the block enclosing the return statement.
所以析构函数在返回值初始化后运行,因此在第一次调用函数时返回值为 0。
关于c++ - 究竟什么时候复制返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35177608/