c++ - 究竟什么时候复制返回值

标签 c++ c++11 visual-c++

假设我有以下代码:

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/

相关文章:

C++,需要错误 : cannot convert parameter 1 from 'char *' to 'const char *&' 的原因

C++ 使用运算符重载转换模板

c++ - 使用 OpenCV 2.4 在 MFC SDI View 或 Control 中加载图像

C++11 - pimpl-idiom 和 unique_ptr 的可能困境?

c++ - 如何定义C结构: c-linkage and udt

c++ - 合并没有空格的文件比有空格更快

c++ - 什么是 'valid' std::function?

c++ - 使用具有不同参数的函数指针的更好设计

c++ - 处理 C 库对象时如何实现 std::move()

c++ - try catch finally construct - 它是在 C++11 中吗?