Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

c++ - Calling virtual method from destructor - workaround?

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? :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...