我问自己以下代码是否安全:
#include <QCoreApplication>
#include <QObject>
#include <QDebug>
#include <QTimer>
class Base : public QObject
{
Q_OBJECT
public:
Base()
{
// is it safe to do that ?
connect(this, SIGNAL(signal1()), this, SLOT(slot1()));
}
virtual ~Base() {}
signals:
void signal1();
public slots:
virtual void slot1() = 0; // could be only virtual
};
class Derived : public Base
{
Q_OBJECT
public slots:
virtual void slot1()
{
qDebug() << "derived slot";
}
void emitSignal1()
{
emit signal1();
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Derived d;
QTimer::singleShot(0, &d, SLOT(emitSignal1()));
return a.exec();
}
#include "main.moc"
输出如预期:
derived slot
我没有看这个connect
方法在幕后做了什么,但我想这就像设置一个回调函数。
如果在类构造函数中没有调用虚拟方法Base
,那么到目前为止我没有看到任何副作用,但这是真的吗?
谢谢你。