Reputation: 2264
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?
Upvotes: 0
Views: 432
Reputation: 170203
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).
Upvotes: 7