Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-119369

Prefer "create" function over default constructor for C++ singletons exposed to QML

    XMLWordPrintable

Details

    Description

      https://doc.qt.io/qt-6/qqmlengine.html#QML_SINGLETON says:

      By default, each QQmlEngine will try to create a singleton instance using either the type's default constructor or a static factory function of the signature T *create(QQmlEngine *, QJSEngine *) when the type is first accessed. If both do exist and are accessible, the default constructor is preferred.

      The current approach requires the user to have a dummy argument in the type's constructor if they also want to use Q_GLOBAL_STATIC, otherwise the QML engine creates a separate singleton, resulting in two instances and some interesting debugging sessions. Making the default constructor inaccessible isn't an option because Q_GLOBAL_STATIC needs it. See the attached example for a demonstration of this, where two singletons are created.

      It would be better if the create function would be used instead of the default constructor if it's available. It is there for a very specific purpose, so it makes sense that it takes priority. This allows users to use Q_GLOBAL_STATIC and not have duplicate singleton instances.

      Attachments

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

        Activity

          People

            qtqmlteam Qt Qml Team User
            mitch_curtis Mitch Curtis
            Votes:
            2 Vote for this issue
            Watchers:
            4 Start watching this issue

            Dates

              Created:
              Updated:

              Gerrit Reviews

                There are no open Gerrit changes