从析构函数调用虚方法

编程入门 行业动态 更新时间:2024-10-27 11:16:20
本文介绍了从析构函数调用虚方法 - 解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要为基类 Base 的所有后代声明finalise方法 finalize()在破坏期间调用,我的意图是从〜Base(),但c ++禁止这样的事情。所以我的问题是

我们如何要求后代以正确和初步的方式完成某些工作?

该代码不能编译:

#include< QDebug> class Base { public: Base(){} virtual〜Base(){ qDebug(deleting b); finalize(); } virtual void finalize()= 0; }; class A:public Base { public: A(){} 〜A(){} void finalize ){qDebug(called finalize in a);} }; int main(int argc,char * argv []) { Base * b = new A; delete b; }

如果我使 Base :: finalize / code>不是纯虚拟,它从〜Base()调用,而不会分派给孩子,因为它已经被销毁。

我可以从孩子的析构函数调用finalize(),但问题是如何强制这样做。换句话说,我的问题是:是否有可能迫使谁写的Base类的后代使用finalizing方法,好吧,在另一种方式,而不是在文档中注释? :)

解决方案

析构函数是发布获得的资源的合适地方,但每个类都负责释放自己的资源。 A类获取的资源不应该(而且不能)由 class Base 发布。

定义虚拟析构函数允许在删除 class Base 时指向类A code>指向类A 对象

p = new A; delete p; // A和Base析构函数被顺序调用!

所以要实现适当的资源释放,你只需要在自己的析构函数中释放每个类的资源。 / p>

I need to declare finalizing method finalize() for all descendants of the base class Base, that should be called during destruction, and my intent was to call pure virtual void Base::finalize() = 0 from the ~Base(), but c++ forbids such a thing. So my question is

How can we oblige descendants to do some finalizing work in right and preliminary defined way?

That code cannot be compiled:

#include <QDebug> class Base { public: Base(){} virtual ~Base(){ qDebug("deleting b"); finalize(); } virtual void finalize() = 0; }; class A : public Base { public: A(){} ~A(){} void finalize(){qDebug("called finalize in a");} }; int main(int argc, char *argv[]) { Base *b = new A; delete b; }

If I make Base::finalize() not pure virtual, it is called from ~Base() without dispatching to child since it have been already destructed.

I can call finalize() from child's destructor but question is how to force to do that. In other words my question is: is it possible to oblige people who will write descendants of the Base class to use finalizing method, well, in another way than commenting it in a documentation? :)

解决方案

Destructors are the right place to release acquired resources, but each class is responsible to release its own resources. Resources acquired by class A should not (and just can not) be released by class Base.

Defining virtual destructors allows class A's destructor to be called when deleting a pointer to class Base pointing to a class A object

Base* p = new A; delete p; // Both A and Base destructors are sequencially called!

So to achieve proper resource release you just have to release each class' resources in its own destructor.

更多推荐

从析构函数调用虚方法

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

发布评论

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

>www.elefans.com

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