自动销毁对象,即使在显式调用析构函数之后也是如此 [英] Automatic destruction of object even after calling destructor explicitly

查看:98
本文介绍了自动销毁对象,即使在显式调用析构函数之后也是如此的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序:

#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.

这篇关于自动销毁对象,即使在显式调用析构函数之后也是如此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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