是否有效直接调用(虚拟)析构函数? [英] Is it valid to directly call a (virtual) destructor?

查看:242
本文介绍了是否有效直接调用(虚拟)析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此答案 ,Ryan直接调用虚析构函数。我测试了VS2010中的代码,它正确地调用所有析构函数(用日志语句测试)。这是真的有效吗?这种方法的问题,缺点甚至是好点?

In this answer, Ryan directly calls the virtual destructor. I've tested the code in VS2010, and it correctly calls all destructors (tested with logging statements). Is it actually valid to do so? What are the problems, flaws or even the good points of such an approach?

我只能认为它是一种真正强制重置实际类型的方法,即使他们不重写一个虚拟 reset 函数,因为他们至少必须清理它们的析构函数。

I can only think of it as a way to really force a reset of the actual type, even if they don't override a virtual reset function, since they atleast have to clean up in their destructors.

还有,调用析构函数带来什么样的副作用?在这样的析构函数调用之后使用对象是未定义的行为吗?如果立即用 new(this)MyClass();

Also, eactly what kind of side-effects does a call to the destructor bring? Is it undefined behaviour to use the object after such a destructor call? What if one immediatly reinitializes it with a new (this) MyClass(); call?

推荐答案

手动调用析构函数是一个完全有效的事情,不管它是否是虚拟的。你只需要确保每次调用构造函数时只调用一次。

Calling a destructor manually is a perfectly valid thing, regardless of if it's virtual. You just want to make sure that it's just called once for every constructor call.

Is it undefined behaviour to use the object after such a destructor call? 

是的。

What if one immediatly reinitializes it with a new (this) MyClass(); call?

还是可怕的未定义。

手动销毁对象,除非你必须手动放置它,例如与放置新的或一些等效的,绝对不要重新初始化一个破坏的对象像这样,希望避免UB。类 std :: vector 非常明确地访问被破坏的对象UB,即使你在它的地方创建一个新的元素,它仍然是UB。

Do not manually destruct an object unless you had to manually place it, e.g. with placement new or some equivalent, and definitely do not ever re-initialize a destructed object like that and hope to avoid UB. Classes like std::vector very explicitly make accessing destroyed objects UB, and it remains UB even if you then make a new element in it's place.

这篇关于是否有效直接调用(虚拟)析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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