gpt4 book ai didi

c++ - CRTP 导致段错误

转载 作者:行者123 更新时间:2023-11-30 02:28:17 26 4
gpt4 key购买 nike

我有一个纯虚类接口(interface):

class Interface {
public:
virtual ~Interface() noexcept;
virtual void open()=0;
virtual void close()=0;
protected:
explicit Interface(const string params);
string params_;
}

然后我有一个抽象类来实现我的业务逻辑:

template<typename T>
class AbstractInterface : public Interface {
public:
void open() override;
void close() override;
void read_is_complete(const vector<byte_array>);
protected:
explicit AbstractInterface(const string params);
virtual ~AbstractInterface() noexcept;
}

然后是使用CRTP实现多态的接口(interface)实现:

class SPInterface : public AbstractInterface<SPInterface> {
public:
explicit SPInterface(const string params);
virtual ~SPInterface() noexcept;
void open();
void close();
void read_is_complete(const vector<byte_array> data);
}

我有一个单元测试,我在其中创建了一个 SPInterface 实例:

unique_ptr<Interface> intf;
intf.reset(new SPInterface("aaa"));

让它超出范围会调用析构函数 AbstractInterface,后者又会调用 AbstractInterface 上的关闭方法,然后在 this 上发生段错误:

template<typename T>
void AbstractInterface<T>::close() {
static_cast<T *>(this)->close();
params_ = "";
}

这令人困惑,因为我已经创建了该类的一个实例。 lldb 似乎证实:

AbstractInterface<SPInterface>::close(this=<unavailable>)

最佳答案

Letting this get out of scope calls the destructor AbstractInterface which in turn calls the close method on AbstractInterface and then it segfaults on this:

template<typename T>
void AbstractInterface<T>::close() {
static_cast<T *>(this)->close();
params_ = "";
}

您似乎正试图从基类的析构函数中调用派生类的方法。
这一点都不安全,段错误 是可执行文件必须告诉您它不同意的方式。 :-)

即使 CRTP 允许您在(让我说)活对象上调用属于派生类的成员函数,它也不会改变对象的析构方式。
不要忘记,基类和成员的销毁顺序与其构造函数的完成顺序相反

关于c++ - CRTP 导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40920062/

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