C++ 析构函数和函数调用顺序

标签 c++ destructor

假设我有以下片段:

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/

相关文章:

c++ - 了解二进制转换

c++ - 这段代码有什么错误,请帮助:

c# - 对象实例丢失时如何处理它的引用

c++ - 从指针 typedef 生成指向 const 对象的指针

c++ - 我可以在 C++ 中同时分配 2 个变量吗?

c++ - strptime 作为 Unresolved reference

c++ - 在 C++ 中如何将方法指定为析构函数而不是构造函数?

C++/析构函数 - 运算符删除

c++ - 在 C++ 的析构函数中删除指针后,将 NULL 分配给指针是否有任何用处?

c# - .NET 中的 C# 类何时调用析构函数?