Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[solved] access data globally within application



  • I am developing qt application which users can log. what is the best way to keep user details access globally within a application. global variable or static variable or there is another better way?


  • Lifetime Qt Champion

    Hi,

    It's not the role of static variables and global variables are rather frown upon. You should rather consider using a singleton for that kind of things



  • can you explain more about singleton and its implementation. may be tutorial about how to use singleton on qt?



  • The singleton is part of the software design patterns.

    The implementation is easy: make the ctor private and implement one public static function which creates the instance:

    class Foo {
        private:
          static Foo* _instance;
          Test();
        public:
         static Foo* getInstance() {
          if (_instance==NULL)
            _instance = new Foo();
          return _instance;
        }
    

    cpp:

    Foo::_instance = NULL;
    

    And, please, put not all 'global variables' into one place, but consider the SOLID principles ;)


Log in to reply