将 CRTP 用于析构函数是否安全?

Is it safe to use CRTP for destructor?

CRTP 可以像虚函数一样调用子 class 方法,尽管虚函数在运行时被解析。

据我所知,在析构函数中调用虚函数是不安全的。 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->运行。 在 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?

不安全。同样的考虑也适用。在构造函数或析构函数中,没有派生对象yet/anymore。因此调用它的成员函数,无论是通过 CRTP 还是通过虚函数和非虚成员间接调用,都会导致未定义的行为。

不幸的是,你的第二个例子仍然有未定义的行为。你 may not static_cast<>(this) to anything other than to cv-qualified void or void*, or to a baseRun 不是)。