CRTP可以像虚函数一样调用子类方法,尽管虚函数是在运行时解析的。
据我所知,在析构函数中调用虚函数是不安全的。CRTP 也是如此吗?使用 CRTP 调用子方法是否安全?
编辑:
如果不是不安全,那么多继承情况呢?例如,
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> {
};
这里,销毁的顺序是A->CRTP->Run。在CRTP的析构函数中调用Run函数安全吗?
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?
不安全。同样的考虑也适用。在构造函数或析构函数中,没有派生对象 yet/anymore。因此调用它的成员函数,无论是通过 CRTP 还是通过虚函数和非虚成员间接调用,都会导致未定义的行为。
不幸的是,你的第二个例子仍然有未定义的行为。你may not static_cast<>(this)
除了 cv-qualified void
或 void*
, or to a base (Run
不是)。
我是一名优秀的程序员,十分优秀!