c++ - Qt disconnectNotify() 未在接收器对象销毁时调用

标签 c++ qt

我有一个发出信号 S 的 C 类。S 可以连接到零个或一个或多个接收器 (R)(连接的数量随时间变化,连接 sw 由接收器建立)。

当 S 的监听器数量大于零时,C 需要做一些事情,当 S 上的监听器数量回到零时,C 需要做其他事情。

我认为我可以使用:

connectNotify()

disconnectNotify()

好吧,...

我注意到 connectNotify() 函数运行良好,但当接收对象被销毁时,disconnectNotify() 没有被调用(在类 C 中)。只有在使用 disconnect() 显式断开连接时才会调用它。

在监听器的析构函数中添加显式断开连接也不是很成功:退出整个应用程序时出现段错误。 (我想当一切都崩溃时尝试使用 disconnect() 不是很好。)

当 R 被销毁时,我尝试使用从 R 实例发送到 C 的 destroy() 信号:这有效,但我如何确定 R 在销毁时已连接? (接收者R可能处于非连接状态):

在 C 类中,插槽 X(在接收到 R 的 destroyed() 时调用)检查 QObject::receivers(),似乎在执行销毁之前返回接收者的数量。由于我不知道被销毁的对象是否已连接,所以我被卡住了!

有什么想法吗?

最佳答案

如果你能确保所有 R 在 C 之前被销毁,你就可以在类 C 中自己管理连接:

头文件:

#include <QtCore/QSet>

class C : (...)
{
    (...)

public:
    void connectReceiver( QObject* receiver );

private slots:
    void handleReceiverDestruction( QObject* receiver );

private:
    QSet< QObject* > _connectedReceivers;
};

源文件:

void C::connectReceiver( QObject* receiver  )
{
    // nothing to do if the receiver is already connected
    if( _connectedReceivers.contains( receiver  ) ) return;

    _connectedReceivers.append( receiver )

    connect( ... ); // <- do your connection(s) here
    connect( receiver, SIGNAL( destroyed                ( QObject* ) ), 
             this    , SLOT  ( handleReceiverDestruction( QObject* ) ) );
}

void C::handleReceiverDestruction( QObject* receiver )
{
    if( !_connectedReceivers.contains( receiver ) )
    {
        // if this happens, a receiver R's destroyed() signal was connected to
        // this function altough R is not a receiver of signal X.
        Q_ASSERT( false );
        return;
    }

    disconnect( ... ); // <- one or more might be necessary here

    _connectedReceivers.remove( receiver );
}

提示:我没有测试编译或逻辑错误,但你应该明白了。

就个人而言,我可能会添加以下内容:

C::~C()
{
    if( !_connectedReceivers.isEmpty() )
    {
        // If you land here, a receiver was not (properly) destroyed before this object
        Q_ASSERT( false );
    }
}

关于c++ - Qt disconnectNotify() 未在接收器对象销毁时调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9564983/

相关文章:

c++ - 在搜索 -ldeepsort 时跳过不兼容的 ../tracker/libdeepsort.so

c++ - 使用 Qt 绘制抛物线或任何其他多项式

qt - 如何编写自定义键盘快捷键

c++ - int64 C++ debian6

c++ - winHTTP GET 请求 C++

c++ - 怎么解决另一个版本的数郎

qt - 学习诺基亚应用从哪里开始?

c++ - 使用每个实例颜色和偏移的 OpenGL 实例渲染

c++ - 无法在QT编辑器中创建调试引擎

c++ - 简单多态转换不起作用