C ++析构函数函数调用顺序 [英] C++ destructor & function call order

查看:189
本文介绍了C ++析构函数函数调用顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下摘要:

Foo foo;
....
return bar();

现在,C ++标准是否可以保证bar()在foo ::〜Foo之前​​被调用? ()?还是这是编译器/实现的选择?

Now, does the C++ standard guarantees me that bar() will be called before foo::~Foo() ? Or is this the compiler/implementation's choice?

谢谢!

推荐答案

保证行为。实际的执行展开如下:

It is guaranteed behaviour. The actual execution is unrolled as follows:

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()

以下是标准的一些参考:

Here are some references from the standard:


  • 一般来说,程序执行保证什么

1.9程序执行

10每个具有自动存储持续时间(3.7.2)的对象的实例是与每个对象相关联的

10 An instance of each object with automatic storage duration (3.7.2) is associated with each entry into its block.




  • foo 具有自动存储期限,并且:

    • The foo is of automatic storage duration and:

    • 3.7.2自动存储期限

      3.7.2 Automatic storage duration

      1显式声明为auto或register或未显式声明的
      static或extern的本地对象具有自动存储期限。
      这些对象的存储将持续到创建它们的块退出为止。

      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.




      • 返回声明的实际影响是什么


      • 6.6.3返回声明

        6.6.3 The return statement

        2(...)表达式的值返回给函数的调用者

        2 (...) the value of the expression is returned to the caller of the function


        6.6跳转语句(返回属于跳转语句)

        2在退出范围(无论完成多少)时,将为所有具有自动存储持续时间(3.7.2)的
        构造对象调用析构函数(12.4)

        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声明语句

        6.7 Declaration statement

        2在块中声明具有自动存储期限的变量在退出块时被破坏

        2 Variables with automatic storage duration declared in the block are destroyed on exit from the block


        12.4析构函数

        12.4 Destructors

        有10个析构函数在程序终止
        (3.6.3)时隐式调用(1)具有静态存储持续时间
        (3.7.1)的构造
        对象,(2)构造对象
        隐式调用在创建
        对象的块退出时(6.7)自动存储持续时间
        (3.7.2)

        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 ++标准中的单个想法表单细节并不容易。希望快速概述也会帮助您自己进行这种分析。

        It is not easy to grasp single idea form details scattered around all the C++ standard. Hopefully, quick overview will help you to make such analysis yourself too.

        这篇关于C ++析构函数函数调用顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆