Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. const global variable outside of constructors

const global variable outside of constructors

Scheduled Pinned Locked Moved Solved General and Desktop
14 Posts 7 Posters 4.5k Views
  • 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.
  • mrjjM Offline
    mrjjM Offline
    mrjj
    Lifetime Qt Champion
    wrote on last edited by mrjj
    #2

    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
    0
    • mrjjM 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 Offline
      M Offline
      marlenet15
      wrote on last edited by
      #3

      @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.

      mrjjM 1 Reply Last reply
      0
      • M marlenet15

        @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.

        mrjjM Offline
        mrjjM Offline
        mrjj
        Lifetime Qt Champion
        wrote on last edited by
        #4

        @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
        0
        • M marlenet15

          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 Offline
          K Offline
          koahnig
          wrote on last edited by koahnig
          #5

          @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
          0
          • Chris KawaC Offline
            Chris KawaC Offline
            Chris Kawa
            Lifetime Qt Champion
            wrote on last edited by
            #6

            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
            1
            • kshegunovK Offline
              kshegunovK Offline
              kshegunov
              Moderators
              wrote on last edited by
              #7

              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
              2
              • Chris KawaC Offline
                Chris KawaC Offline
                Chris Kawa
                Lifetime Qt Champion
                wrote on last edited by
                #8

                @kshegunov said:

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

                Preach it brother! ;)

                kshegunovK 1 Reply Last reply
                0
                • Chris KawaC Chris Kawa

                  @kshegunov said:

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

                  Preach it brother! ;)

                  kshegunovK Offline
                  kshegunovK Offline
                  kshegunov
                  Moderators
                  wrote on last edited by
                  #9

                  @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
                  0
                  • kshegunovK kshegunov

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

                    A Offline
                    A Offline
                    ambershark
                    wrote on last edited by
                    #10

                    @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

                    kshegunovK 1 Reply Last reply
                    0
                    • K Offline
                      K Offline
                      koahnig
                      wrote on last edited by
                      #11

                      @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
                      0
                      • A ambershark

                        @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. :)

                        kshegunovK Offline
                        kshegunovK Offline
                        kshegunov
                        Moderators
                        wrote on last edited by
                        #12

                        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 JKSHJ 2 Replies Last reply
                        0
                        • kshegunovK kshegunov

                          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 ...

                          A Offline
                          A Offline
                          ambershark
                          wrote on last edited by
                          #13

                          @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
                          0
                          • kshegunovK kshegunov

                            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 ...

                            JKSHJ Offline
                            JKSHJ Offline
                            JKSH
                            Moderators
                            wrote on last edited by JKSH
                            #14

                            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
                            0

                            • Login

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • Users
                            • Groups
                            • Search
                            • Get Qt Extensions
                            • Unsolved