从析构函数调用虚方法 - 解决方法? [英] Calling virtual method from destructor - workaround?

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

问题描述

我需要为基类 Base 的所有后代声明finalise方法 finalize()在破坏期间调用,我的意图是从〜Base() virtual void Base :: finalize()= 0 $ c>,但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.

这篇关于从析构函数调用虚方法 - 解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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