C ++:在事件驱动系统中间接调用`delete this`(例如在GUI应用程序中)

时间:2015-06-16 07:13:21

标签: c++ user-interface event-handling

我使用不同的C ++ GUI框架工作了一段时间(例如Qt,wxWidgets,也有一些专有),但无法自行决定下面描述的主题。

正如在这里的几个问题/答案中所讨论的,直接使用delete this在C ++中是有效的(只要你不再解除引用this),但在大多数情况下不太好主意。

但在某些情况下,object会间接调用它的析构函数。这种情况经常出现在事件驱动系统中(首先想到GUI应用程序)。

class Kernel {
public:
    void Start() {
        _window = new Window();
    }
    void OnCloseButton() {
        if (_window) {
            _window->Close();
            delete _window;
            _window = NULL;
        }
private:
    MyWindow * _window;
};

class MyWindow
{
public:
    MyWindow(Kernel & kernel) : _kernel(&kernel) {
        Connect(my_button_close_event, this, OnCloseButtonClicked);
    }
    OnCloseButtonClicked() {
        // This call actually calls destructor of this object.
        _kernel->OnCloseButton();
        // If we access any fields of Window here, we're going to have problems
    }
private:
    Kernel * _kernel;
};

注意:我没有尝试编译代码 - 它可能有拼写错误或不良做法。但它应该说明这个想法。

所以,问题是:在上面的示例中执行某些操作是否可行:事件的处理程序调用其他函数(其所有者的方法),间接删除this

或者我应该更好地识别Kernel类事件并将事件从按钮直接连接到Kernel中的方法,然后我们没有这种间接调用{{1}的情况}}

提前致谢。

1 个答案:

答案 0 :(得分:0)

可以这样做,因为Window实例是由Start()方法创建的,但它在面向对象编程中是一种不好的做法。