PDA

View Full Version : connect in constructor?



McKee
9th October 2007, 21:43
Hello --

I have a class derived from QObject which has a QTimer member called m_MyTimer. I have a private slot in that object with signature void MyTimeout(). The following call in the class constructor causes a crash.


connect(&m_MyTimer,SIGNAL(timeout()),this,SLOT(MyTimeout()) );

The failure is at the 4th line of the body of the following Qt library function (at the for loop).


int QMetaObject::indexOfSlot(const char *slot) const
{
int i = -1;
const QMetaObject *m = this;
while (m && i < 0) {
for (i = priv(m->d.data)->methodCount-1; i >= 0; --i)
if ((m->d.data[priv(m->d.data)->methodData + 5*i + 4] & MethodTypeMask) == MethodSlot
&& strcmp(slot, m->d.stringdata
+ m->d.data[priv(m->d.data)->methodData + 5*i]) == 0) {
i += m->methodOffset();
break;
}
m = m->d.superdata;
}
return i;
}

In particular, m->d.data is 0.

A workaround is to put the call to connect() in an initialization function that the client of the object is then obliged to call once, but that's annoying. Is there a way to get the connection at construction time?

thanks

jacek
9th October 2007, 21:57
Do you have any static or global variables in your application?

McKee
13th October 2007, 19:05
Yes, the object itself is global ... I sense a newbie moment approaching ... why, does that affect order of construction of the object?

marcel
13th October 2007, 19:08
All QObjects have to be createad after a QAppliaction object has been instantiated.

jacek
13th October 2007, 21:53
why, does that affect order of construction of the object?
I think you are experiencing a static initialization order fiasco (http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12). It's easy to stumble upon it in Qt, because every class with Q_OBJECT macro has a static member variable with meta-data and if you initialize your object before that meta-data object was created, you hit a null pointer.

Also, as Marcel has already said, you should create all Qt objects after QApplication instance was created, since only then Qt is fully initialized. This especially applies to fonts, codecs and everything that has something to do with plugins.