自动销毁对象,即使在显式调用析构函数之后也是如此

编程入门 行业动态 更新时间:2024-10-26 20:30:16
本文介绍了自动销毁对象,即使在显式调用析构函数之后也是如此的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下程序:

#include <iostream> using namespace std; class Test { public: Test() { cout << "Constructor is executed\n"; } ~Test() { cout << "Destructor is executed\n"; } }; int main() { Test(); // Explicit call to constructor Test t; // local object t.~Test(); // Explicit call to destructor return 0; }

打印以下输出:

Constructor is executed Destructor is executed Constructor is executed Destructor is executed Destructor is executed

我的问题甚至是在main()中显式调用析构函数之后,为什么编译器在退出main()之前隐式调用析构函数?

My question is even after explicitly calling destructor in main(), why does the compiler call the destructor implicitly before exiting main()?

作为附带的问题,除了在delete运算符中使用之外,显式调用析构函数的策略还有其他用途吗?

As a side question, apart from use in delete operator is there any other use of the strategy of calling destructor explicitly?

推荐答案

您已经引入了未定义的行为.

You've introduced undefined behavior.

按照标准:

§12.4析构函数

§ 12.4 Destructors

(11)析构函数被隐式调用

(11) A destructor is invoked implicitly

(11.3)— 用于当对象所在的块所在时具有自动存储持续时间(3.7.3)的构造对象 创建的出口(6.7),

(11.3) — for a constructed object with automatic storage duration (3.7.3) when the block in which an object is created exits (6.7),

15一旦为一个对象调用了析构函数,该对象就不再存在;如果 对于生命周期已结束的对象(3.8)调用析构函数. [示例:如果析构函数为 显式调用自动对象,然后以通常的方式保留该块 调用对象的隐式销毁,行为是不确定的. —完示例]

15 Once a destructor is invoked for an object, the object no longer exists; the behavior is undefined if the destructor is invoked for an object whose lifetime has ended (3.8). [ Example: if the destructor for an automatic object is explicitly invoked, and the block is subsequently left in a manner that would ordinarily invoke implicit destruction of the object, the behavior is undefined. —end example ]

您显式调用析构函数或通过调用t.~Test(),然后在对象离开作用域时隐式调用它.这是未定义的.

You explicitly call the destructor or by calling t.~Test(), it is then implicitly invoked when the object leaves scope. This is undefined.

该标准也提供了此注释:

The standard provides this note as well:

14 [注意:很少需要析构函数的显式调用.此类调用的一种用法是将对象放置在特定位置 使用展示位置new-expression的地址.显式放置和破坏对象的这种使用可以 是应付专用硬件资源和编写内存管理工具所必需的.

14 [ Note: explicit calls of destructors are rarely needed. One use of such calls is for objects placed at specific addresses using a placement new-expression. Such use of explicit placement and destruction of objects can be necessary to cope with dedicated hardware resources and for writing memory management facilities.

更多推荐

自动销毁对象,即使在显式调用析构函数之后也是如此

本文发布于:2023-10-26 21:46:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531439.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!