gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:12:32 24 4
gpt4 key购买 nike

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 voidvoid* , or to a base (Run 不是)。

关于c++ - 将 CRTP 用于析构函数是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50042466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com