假设我有以下片段:
Foo foo;
....
return bar();
现在,C++ 标准是否保证我会在 foo::~Foo() 之前调用 bar() ?或者这是编译器/实现的选择?
谢谢!
最佳答案
这是有保证的行为。实际执行展开如下:
0: enter block (scope)
1: Foo::Foo()
2. evaluation of bar(); as expression in return statement
3. save result of the expression as value returned from function
4. finalize return statement to leave function to its caller (request exit from current scope)
5: exit block (scope) with call to Foo::~Foo()
以下是标准中的一些引用:
- 程序执行一般保证什么
1.9 Program execution
10 An instance of each object with automatic storage duration (3.7.2) is associated with each entry into its block.
foo
具有自动存储期限,并且:
3.7.2 Automatic storage duration
1 Local objects explicitly declared auto or register or not explicitly declared static or extern have automatic storage duration. The storage for these objects lasts until the block in which they are created exits.
- return 语句的实际作用是什么
6.6.3 The return statement
2 (...) the value of the expression is returned to the caller of the function
和
6.6 Jump statements (return belongs to jump statements)
2 On exit from a scope (however accomplished), destructors (12.4) are called for all constructed objects with automatic storage duration (3.7.2)
- 什么保证效果发生
6.7 Declaration statement
2 Variables with automatic storage duration declared in the block are destroyed on exit from the block
和
12.4 Destructors
10 Destructors are invoked implicitly (1) for a constructed object with static storage duration (3.7.1) at program termination (3.6.3), (2) for a constructed object with automatic storage duration (3.7.2) when the block in which the object is created exits (6.7)
要掌握分散在所有 C++ 标准中的单一想法形式的细节并不容易。希望快速概述也能帮助您自己进行此类分析。
关于C++ 析构函数和函数调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2196327/