Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct

    Solved const global variable outside of constructors

    General and Desktop
    7
    14
    3647
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • M
      marlenet15 last edited by

      I have three constructors and each time it needs to initialize the same variables with the same values (they are constant). These variables are also used throughout the class. My problem is that I can't seem to make them global by being outside of the constructors since I am trying to work with QFiles. I have tried many different ways but nothing seems to work. Here is what I have now:

      test.h

      class Test
      {
      .
      .
      private:
         QDir _userDir;
         const static QString path;
         const static QFile _activeFile;
         const static QFile _deletedFile;
      };
      
      const QString Test::path = QDir::homePath() + "/files/";
      const QFile Test::_activeFile = Test::_activeFile.setFileName(Test::path + "active");
      const QFile Test::_deletedFile = QFile(Test::path + "deleted");
      

      Is it possible to make this work?

      K 1 Reply Last reply Reply Quote 0
      • mrjj
        mrjj Lifetime Qt Champion last edited by mrjj

        Hi
        You can init const members via the constructor
        http://stackoverflow.com/questions/14495536/how-to-initialize-const-member-variable-in-a-class-c

        But after reading your post again, Im not sure what the real issue is?

        M 1 Reply Last reply Reply Quote 0
        • M
          marlenet15 @mrjj last edited by

          @mrjj I have several constructors and instead of initializing those variables in every constructor, I would like to find a way to initialize them so that they can all use them.

          mrjj 1 Reply Last reply Reply Quote 0
          • mrjj
            mrjj Lifetime Qt Champion @marlenet15 last edited by

            @marlenet15
            if you have c++11 you can have one constructor call another
            https://en.wikipedia.org/wiki/C%2B%2B11#Object_construction_improvement

            What is wrong with the out of class init of them ?

            1 Reply Last reply Reply Quote 0
            • K
              koahnig @marlenet15 last edited by koahnig

              @marlenet15 said:

              I have three constructors and each time it needs to initialize the same variables with the same values (they are constant). These variables are also used throughout the class. My problem is that I can't seem to make them global by being outside of the constructors since I am trying to work with QFiles. I have tried many different ways but nothing seems to work. Here is what I have now:

              test.h

              class Test
              {
              .
              .
              private:
                 QDir _userDir;
                 static const QString path;      // <<< static and const exchanged 
                 static const QFile _activeFile;      // <<< static and const exchanged 
                 static const QFile _deletedFile;      // <<< static and const exchanged 
              };
              
              const QString Test::path = QDir::homePath() + "/files/";
              const QFile Test::_activeFile = Test::_activeFile.setFileName(Test::path + "active");      // <<< this will not work. This is somehow recursive
              const QFile Test::_deletedFile = QFile(Test::path + "deleted");
              

              Is it possible to make this work?

              I have added some remarks to your source
              In addition to @mrjj what already wrote, you can use the same init routine in every version of your contructors.

              Vote the answer(s) that helped you to solve your issue(s)

              1 Reply Last reply Reply Quote 0
              • Chris Kawa
                Chris Kawa Moderators last edited by

                My 0.02$:

                There are simple syntactic problems in your declararion (e.g. self reference in _activeFile initialization), but I think you focused on the wrong thing altogether. All this is a needless micro-optimization.
                We're talking about files here. A single tiny I/O in any file will take waaaaay more time than a simple call like this:

                QFile activeFile(QDir::homePath() + "/files/active");
                

                so just make it a local variable where you need it.
                Besides, you said these would be used throughout your class. You're unlikely going to be accessing the same file from many instances of your class, so this sounds a lot like this classes state. As such it should either be a local variable in the methods or, at most, a non-static member initialized at first use, not up front.

                1 Reply Last reply Reply Quote 1
                • kshegunov
                  kshegunov Moderators last edited by

                  Hello,
                  I have few objections as well:

                  1. One static variable depends on another for being initialized.
                  2. You're copying QFile objects, which is not allowed
                  3. (Possibly) You've put the definitions in the header file

                  There are more, but I guess I should stop at some point with my crusade against static variables ...

                  Kind regards.

                  Read and abide by the Qt Code of Conduct

                  1 Reply Last reply Reply Quote 2
                  • Chris Kawa
                    Chris Kawa Moderators last edited by

                    @kshegunov said:

                    but I guess I should stop at some point with my crusade against static variables ...

                    Preach it brother! ;)

                    kshegunov 1 Reply Last reply Reply Quote 0
                    • kshegunov
                      kshegunov Moderators @Chris Kawa last edited by

                      @Chris-Kawa
                      Wow, I'm glad I'm not the only one! :)

                      Read and abide by the Qt Code of Conduct

                      A 1 Reply Last reply Reply Quote 0
                      • A
                        ambershark @kshegunov last edited by

                        @kshegunov I have been bit so many times by global/static variables lately that I'm done using them entirely. Along with singleton classes. So consider me converted to your cause. :)

                        My L-GPL'd C++ Logger github.com/ambershark-mike/sharklog

                        kshegunov 1 Reply Last reply Reply Quote 0
                        • K
                          koahnig last edited by

                          @kshegunov

                          I am another one seeing the use of static instances with shudder.

                          For sure some preaching in this forum does in my opinion a lot good. For many is the static declaration the first and best of alternatives, but as indicated by others this may haunt them forever or until they decide to rewrite the whole stuff.

                          Banning entirely is not necessarily the best of choices either. However, thinking more than twice is a good advice.

                          Vote the answer(s) that helped you to solve your issue(s)

                          1 Reply Last reply Reply Quote 0
                          • kshegunov
                            kshegunov Moderators @ambershark last edited by

                            Sounds like a religion brewing up ;)

                            @ambershark

                            I have been bit so many times by global/static variables lately that I'm done using them entirely. Along with singleton classes. So consider me converted to your cause. :)

                            As to global/static variables, I relate to @koahnig's sentiment - sometimes they're necessary, but not in most cases. The singleton is another kettle of fish entirely ... one of the most useless things one could come up with. Basically you get your static functions and artificially make them nonstatic, but by using a global object you gain nothing really ... strange stuff that singleton pattern ...

                            Read and abide by the Qt Code of Conduct

                            A JKSH 2 Replies Last reply Reply Quote 0
                            • A
                              ambershark @kshegunov last edited by

                              @kshegunov The one thing I always end up making a singleton is a logger. I just can't think of a good way to make a logger component that can be used by any part of your application and it's libraries to be easy to use without a singleton type interface. It just makes it so easy to auto logger = Logger::instance() and have it created and logfiles open, levels set, etc.

                              I don't use a lot of singletons but there are certain things like the logger that I just don't see better ways to handle. Although I'm sure that is me just not putting enough effort into finding a better way. We tend to go with what we've done in the past as the path of least resistance on a new project. And I admit I haven't put much thought into a logger since I used a singleton one many years back. :)

                              And I'm not completely against statics, just sick of dealing with initialization of them. Especially on OSX where things get really weird when you use something in a dylib and an exe. I find there are good places for them..

                              Recently I had a base class that had a bunch of TLV data that would be put into a map. There were then about 80 derived classes from this base. So that data would be allocated in memory 80 times. Seemed like a waste. Static was a good route there since that data was pretty much just const data anyway.

                              Usually when statics/globals bite me it's cause of a singleton thing (usually a Logger), but sometimes things like a state machine or something else that lends itself easily to a singleton.

                              My L-GPL'd C++ Logger github.com/ambershark-mike/sharklog

                              1 Reply Last reply Reply Quote 0
                              • JKSH
                                JKSH Moderators @kshegunov last edited by JKSH

                                In this case, it's not just a question of "are static variables OK?"

                                It is safe to have static QStrings. However, it is NOT safe to have static QFiles. This is because QFiles are QObjects; all QObjects should be created after QCoreApplication and destroyed before QCoreApplication. If you violate this rule, you might experience strange issues.

                                • http://www.ics.com/designpatterns/solutions/qobject-lifecycle.html
                                • http://www.ics.com/designpatterns/book/globals.html

                                Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

                                1 Reply Last reply Reply Quote 0
                                • First post
                                  Last post