C ++ - 析构函数被调用两次 [英] C++ - destructor being called twice

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

问题描述

我在C ++中用这段代码尝试析构函数:

I was experimenting with destructors in C++ with this piece of code:

#include <iostream>

struct temp
{
    ~temp() { std::cout << "Hello!" << std::endl; }
};

int main()
{
    temp t;
    t.~temp();
}

我看到Hello!正在打印两次。不应该调用析构函数释放对象,析构函数在超出范围时不应该再次调用?还是有其他的概念?

I see that "Hello!" is being printed twice. Shouldn't the calling of the destructor free the object and the destructor shouldn't be called again when it goes out of scope? Or is there some other concept?

(我不打算这样做,我只是想了解这里发生了什么。)

(I do not intend to do this in practice. I'm just trying to understand what's going on here.)

推荐答案

这是因为你告诉它发生。当变量超出范围时,自动变量的析构函数总是被调用。你也叫它。这是两个调用总和。

It happens because you told it to happen. The destructor for an automatic variable is always called when the variable goes out of scope. You also called it. That's two calls total.

调用对象的析构函数不会发信号给C ++不再调用它,因为在正常执行中没有必要跟踪。

Calling an object's destructor does not signal to C++ not to call it again, since in normal execution there is no need to keep track.

解决方案是永远不要手动调用你的析构函数。

The solution is to never manually call your destructor.

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

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