简体   繁体   中英

Is it safe to use CRTP for destructor?

CRTP can call child class method like virtual function although virtual function is resolved while runtime.

As far as I know, it is not safe to call virtual function in a destructor. Is same thing true for CRTP? Is it safe or unsafe to call child method using CRTP?

Edit:

If it is not unsafe, what about multiple inheritance case? For instance,

template<typename T, typename V>
struct CRTP {
    ~CRTP()
    {
        static_cast<V*>(static_cast<T*>(this))->run();
    }
};

struct Run {
    void run() { std::cout << "run" << std::endl; }
};

struct A : Run, CRTP<A, Run> {

};

Here, the order of destruction is A->CRTP->Run. Is it safe to call functions of Run in destructor of CRTP?

As far as I know, it is not safe to call virtual function in a destructor. Is same thing true for CRTP? Is it safe or unsafe to call child method using CRTP?

It is not safe. The very same considerations apply. In the constructor or the destructor, there is no derived object yet/anymore. So calling its member function, be it by CRTP or by cheating with virtual functions and indirection via non-virtual members, leads to undefined behavior.

Your second example still has undefined behavior, unfortunately. You may not static_cast<>(this) to anything other than to cv-qualified void or void* , or to a base (which Run is not).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM