【问题标题】:Qt Destructor doesn't disconnect signal/slotQt Destructor 不会断开信号/插槽
【发布时间】:2019-02-12 18:07:54
【问题描述】:

我发现 Qt 的这种奇怪行为: 我希望如果对象被破坏,它会自动断开连接到其插槽的所有“传入”信号。但是,下面这个小例子演示了,如果信号是从类成员的析构函数发出的(在主类的析构函数之后自动调用),它仍然会被主类的槽接收到。

我有一个实际不存在的对象的插槽调用是正常行为吗?文件example.h的源代码:

#include <QObject>
#include <iostream>

class Part: public QObject {
    Q_OBJECT
public:
    Part(QObject *parent = nullptr) : QObject(parent) {
       std::cout << "Part::Part()" << std::endl;
    }
    ~Part() {
       std::cout << "Part::~Part()" << std::endl;
       emit someSignal();
   }
signals:
    void someSignal();
};


class Foo: public QObject {
    Q_OBJECT
public:
    Foo(QObject *parent = nullptr) : QObject(parent) {
        m_part = new Part(this);
        std::cout << "Foo::Foo()" << std::endl;
        connect(m_part, &Part::someSignal, this, &Foo::slotFunc);
    }
    ~Foo() {
        std::cout << "Foo::~Foo()" << std::endl;
    }

public slots:
    void slotFunc() {
        std::cout << "Foo::slotFunc()" << std::endl;
    }
private:
    Part *m_part;
};

main.cpp 文件只包含:

{
    Foo obj;
}

输出是:

Part::Part()
Foo::Foo()
Foo::~Foo()
Part::~Part()
Foo::slotFunc()

【问题讨论】:

  • it should disconnect。如果没有 QApplication 对象和/或事件循环,它可能无法工作?
  • 是的,在这种情况下它真的很有帮助,如果我不是作为控制台应用程序启动它,而是作为带有事件循环的普通小部件应用程序。但接下来,它就像这里写的那样工作,其中 m_part 有一个类型 Part * 和初始化 new Part(this)。但是如果我使用 std::unique_ptr m_part;具有相应的初始化 m_part = std::make_unique();出现上述行为。
  • 请问您使用的是哪个版本的Qt?当我尝试重新制作 [Suse Linux + Qt5.11.1] 时,我没有看到该插槽被调用。
  • 也是 Qt 5.11.1 但在 Windows 7 下:)

标签: qt destructor signals-slots


【解决方案1】:

这显然不会发生 - 至少不是我理解您所做的事情的方式,如果您的代码按面值计算则不会。作为QObject 或QWidget 正在销毁的最终行为之一,涉及给定对象的所有连接都会在该对象的子级被删除之前断开连接。早在 4.8 版之前,Qt 就是这种情况,我在 4.8、5.9、5.10 和 5.11 上检查过它。行为是一样的:你描述的是不可能的。

如果使用foo 具有除Foo 以外的任何类型调用插槽,则下面的测试将导致Foo::slot 内的断言失败。我敦促您下载代码,自己构建并运行它。断言在调试和发布模式下都保留(由于QT_FORCE_ASSERTS),因此发布模式不会使测试无效。代码无需更改即可为您编译 - 如果确实如此,则表明必须首先解决一些其他问题,并且要理解而不是轻视。

Scope 类只是一个助手,用作程序计数器的代理,并且可以断言代码正在做什么。

输出如下(测试的 3 个场景中的第一个):

*** before the application object is created
part_constructor_body *ran*
part_constructor_body *ran*
part_constructor_body *ran*
part_constructor_body *ran*
part_constructor_body *ran*
part_constructor_body *ran*
part_constructor_body *ran*
Foo_Type (enter)
foo_constructor_body (enter)
foo_constructor_body (leave)
foo_destructor_body *ran*
part_destructor_body (enter)
foo_slot_body *ran*
part_destructor_body (leave)
part_destructor_body (enter)
foo_slot_body *ran*
part_destructor_body (leave)
part_destructor_body (enter)
foo_slot_body *ran*
part_destructor_body (leave)
part_destructor_body (enter)
foo_slot_body *ran*
part_destructor_body (leave)
part_destructor_body (enter)
foo_slot_body *ran*
part_destructor_body (leave)
part_destructor_body (enter)
foo_slot_body *ran*
part_destructor_body (leave)
Foo_Type (leave)
part_destructor_body "part4" (enter)
****
part_destructor_body "part4" (leave)

在标记为**** 的地方会有一个foo_slot_body,以及由于断言失败而导致的崩溃。这不会发生。

// https://github.com/KubaO/stackoverflown/tree/master/questions/object-lifetime-conundrum-52221660
#define QT_FORCE_ASSERTS
#include <QtCore>
#include <memory>

static const char kEnter[8] = "(enter)", kLeave[8] = "(leave)", kBlip[6] = "*ran*";
class Scope {
   Q_DISABLE_COPY(Scope)
   QObject *const obj;
   QByteArray const property;
   static QObject &proprietor() {
      static QObject p;
      return p;
   }
   static void indicate(const char *prop, QObject *obj, const char *event) {
      auto dbg = QDebug(QtMsgType::QtDebugMsg) << prop;
      if (!obj->objectName().isEmpty()) dbg << obj->objectName();
      dbg << event;
      Q_ASSERT(isIn(prop) == (event == kLeave));
      proprietor().setProperty(prop, event == kEnter);
   }

  public:
   enum When { Out = 1, InOut = 2 } const when;
   Scope(const char *p, QObject *o, When w = InOut) : obj(o), property(p), when(w) {
      if (when == InOut) in();
   }
   void in() { indicate(property, obj, kEnter); }
   ~Scope() { indicate(property, obj, kLeave); }
   struct GoIn {
      GoIn(Scope &scope) { scope.in(); }
   };
   static void blip(const char *prop, QObject *o) { Scope::indicate(prop, o, kBlip); }
   static void shred(const char *prop) { proprietor().setProperty(prop, {}); }
   static bool had(const char *prop) { return proprietor().property(prop).isValid(); }
   static bool isIn(const char *prop) { return proprietor().property(prop).toBool(); }
};

class Part : public QObject {
   Q_OBJECT
  public:
   Part(QObject *parent = nullptr) : QObject(parent) {
      Scope::blip("part_constructor_body", this);
      Q_ASSERT(!Scope::isIn("Foo_Type"));
   }
   ~Part() override {
      Scope scope("part_destructor_body", this);
      emit signal();
   }
   Q_SIGNAL void signal();
};

class Foo : public QObject {
   Q_OBJECT
   Scope scope{"Foo_Type", this, Scope::Out};
   Part part1{this};  // a child owned by value - bravo! - the lowest overhead approach
   Part part2;        // ditto, made a child in the constructor's initializer list
   Part part3;        // fine, but not a child of Foo, and thus Foo's `moveToThread()`
                      // will almost always set Part up for undefined behavior
   // the below all have the overhead of an extra indirection - an entirely gratuitous one
   std::unique_ptr<Part> part1b{new Part(this)};
   std::unique_ptr<Part> part2b;
   std::unique_ptr<Part> part3b{new Part};
   // and the snafu
   Part *part4{new Part(this)};
   Scope::GoIn into{scope};

  public:
   Foo(Qt::ConnectionType type = Qt::AutoConnection)
       : part2(this), part2b(new Part(this)) {
      Scope scope("foo_constructor_body", this, Scope::InOut);
      part4->setObjectName("part4");
      for (auto *p :
           {&part1, &part2, &part3, part1b.get(), part2b.get(), part3b.get(), part4})
         connect(p, SIGNAL(signal()), this, SLOT(slot()), type);
   }
   ~Foo() override { Scope::blip("foo_destructor_body", this); }

   Q_SLOT void slot() {
      Scope::blip("foo_slot_body", sender());
      Q_ASSERT(qobject_cast<Foo *>(this));
      Q_ASSERT(Scope::isIn("Foo_Type"));  // equivalent to the foregoing assert
   }
};

int main(int argc, char *argv[]) {
   qDebug() << "*** before the application object is created";
   Foo{};
   QCoreApplication app(argc, argv);
   qDebug() << "*** after the application object is created";
   Foo{};
   qDebug() << "*** with queued connections" << Qt::QueuedConnection;
   {
      Q_ASSERT(Scope::had("foo_slot_body"));
      Scope::shred("foo_slot_body");
      Foo foo3(Qt::QueuedConnection);  // check with queued connections
      QTimer::singleShot(1, &app, SLOT(quit()));
      app.exec();
      Q_ASSERT(!Scope::had("foo_slot_body"));
   }
}
#include "main.moc"

【讨论】:

    猜你喜欢
    • 2014-02-18
    • 2012-09-11
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多