For the record it is actually possible (I proved it) to create multiple instances of the same singleton with only one engine using a singleton published from C++ if you concoct your C++ side, um,  poorly. But that's another matter for people stuck before C++11...

I've fixed QTBUG-116432 if that's what you're referring to. See https://codereview.qt-project.org/c/qt/qtdeclarative/+/499804

But for the lay person, what is wrong with ensuring the single singleton approach and why is it so important to you that QML engines MUST own their own singletons?

There are two major reasons:

1. Object ownership: Objects returned from methods (also the create() method) are supposed to be owned by the engine. People don't realize and don't setObjectOwnership() and then their program crashes when the engine terminates and tries to delete the singleton.

2. Thread affinity: The singleton the engine creates lives in the engine's thread. If the singleton returned from create() lives in a different thread and you're not very careful, you get a horrible mess. This can easily happen if your singleton comes from "somewhere" you don't control.

Indeed the same problems surface if you return an object from an invokable method, but singletons are a much more prominent feature in the language, especially since they can often replace context properties. Therefore, I'm spending more effort on recommending the safest possible method to create singletons.

The create() method does require setting C++ ownership (but as we discussed, this breaks down with QML_FORIEGN registrations.

I guess this is about https://bugreports.qt.io/browse/QTBUG-111169 ? If so, the problem is not with any and all QML_FOREIGN registrations. It's just that the auto-generated registrations assume the engine owns the object.

best regards,
Ulf
_______________________________________________
Interest mailing list
Interest@qt-project.org
https://lists.qt-project.org/listinfo/interest

Reply via email to