zet
zet

Reputation: 169

Is it all right to create a QStatemachine object before QApplication object created?

I am using Qt5 to create a Qt application.

Following is my code:

static QStateMachine *myStateMachine = new QStateMachine(nullptr);

I wanna create the QStateMachine just one time, use the same machine all the time.

However, I learn that all QObjects should not be instantiated before QApplication instantiated.You can read Qt document about QApplication's Detailed Description.

My question is:

Why all QObjects should not be instantiated before QApplication instantiated?

Upvotes: 1

Views: 264

Answers (1)

In a 2014 thread on the Qt interest list, Thiago Macieira wrote:

Qt is not supported before the creation of QCoreApplication. Your use-case is not supported, so no answer is necessary.

Just don't do it.

Note: the doc is wrong.

He's a long-term Qt maintainer (and worked for Trolltech). Thus I would generally follow his advice.

What I'd imagine he means is that on various systems--features end up needing some kind of chance at initialization. It may not be all systems, and it may be a need that gets introduced in a later version. The Qt developers thus likely reserve the right to make any given feature require it...and offer no promises that anything in the system will work before the initialization.

(Note: This sort of parallels the concept of undefined behavior in C++)

However, he softens the stance slightly in a later post:

Does that mean static objects aren't supported either?

Not supported, but mostly they work. We will also fix bugs in uses that reasonably could happen in main() while parsing the command-line and other set-up procedures before QCoreApplication gets created.

Just be careful because some things will not work. For example, QString::fromLocal8Bit doesn't work before QCoreApplication.

Point being that giving a list of things you can do before QApplication instantiation today should be considered misleading. They don't want to make that list.

If you find you really have to do it, and you appear get away with it, then be prepared to have it break in a future release (or perhaps even on a different machine).

Upvotes: 2

Related Questions