C++ 自定义信号/槽析构函数问题

问题描述

我正在我的嵌入式项目中处理信号/插槽模块(没有标准库)。它工作正常,但我注意到当它的对象被销毁时我需要释放插槽。我在“memberSlots”命名变量中有插槽列表。 Slot 是一对对象和一个指向其成员函数的指针。 Slot 通过“调用方法执行成员函数。 问题是,当插槽“目标”对象被销毁时,它不会从信号中的 memberSlots 列表中删除,也就是它会在调用发射信号时尝试从销毁的对象指针执行成员函数

信号.h:

#include "slot.h"
#include "list.h"

template<typename Arg,typename RetType = void>
class Signal
{
    List<SlotInterface<Arg>*> memberSlots;
    List<RetType(*)(Arg)> nonMemberSlots;
public:
    ~Signal() {
        for (auto slot : memberSlots) delete slot;
    }
    template<typename Type>
    void attach(Type* object,RetType(Type::* m)(Arg)) {
        nonMemberSlots.pushBack(m);
    }
    void attach(RetType(*m)(Arg)) {
        memberSlots.pushBack(new Slot<Type,Arg,RetType>(object,m));
    }
    void emit(const Arg& arg) {
        for (auto slot : memberSlots) slot->call(arg);
        for (auto slot : nonMemberSlots) slot(arg);
    }
};

slot.h:

template <typename T>
class SlotInterface {
public:
    virtual ~SlotInterface(){}
    virtual void call(T value) = 0;
};

template <typename Target,typename ArgType,typename RetType=void>
class Slot : public SlotInterface<ArgType>
{
    Target* object;
    RetType (Target::*method)(ArgType);
public:
    Slot(Target* object,RetType (Target::*m)(ArgType)) : object(object),method(m) {}
    void call(ArgType value) override {
        (object->*method)(value);
    }
};

是否有任何可靠的解决方案可以在目标类被销毁或类似的情况下删除插槽?我不想手动断开插槽,因为那时我将拥有一个指针并且我试图避免这种情况。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)