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
Forum Updated to NodeBB v4.3 + New Features

const global variable outside of constructors

Scheduled Pinned Locked Moved Solved General and Desktop
14 Posts 7 Posters 4.5k Views 6 Watching
  • 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 Offline
    M Offline
    marlenet15
    wrote on 13 Jan 2016, 19:17 last edited by
    #1

    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 13 Jan 2016, 20:41
    0
    • M Offline
      M Offline
      mrjj
      Lifetime Qt Champion
      wrote on 13 Jan 2016, 19:24 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 13 Jan 2016, 20:28
      0
      • M mrjj
        13 Jan 2016, 19:24

        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 13 Jan 2016, 20:28 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.

        M 1 Reply Last reply 13 Jan 2016, 20:36
        0
        • M marlenet15
          13 Jan 2016, 20:28

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

          M Offline
          M Offline
          mrjj
          Lifetime Qt Champion
          wrote on 13 Jan 2016, 20:36 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
            13 Jan 2016, 19:17

            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 13 Jan 2016, 20:41 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
            • C Offline
              C Offline
              Chris Kawa
              Lifetime Qt Champion
              wrote on 13 Jan 2016, 20:51 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
              • K Offline
                K Offline
                kshegunov
                Moderators
                wrote on 13 Jan 2016, 20:58 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
                • C Offline
                  C Offline
                  Chris Kawa
                  Lifetime Qt Champion
                  wrote on 13 Jan 2016, 21:00 last edited by
                  #8

                  @kshegunov said:

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

                  Preach it brother! ;)

                  K 1 Reply Last reply 13 Jan 2016, 21:03
                  0
                  • C Chris Kawa
                    13 Jan 2016, 21:00

                    @kshegunov said:

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

                    Preach it brother! ;)

                    K Offline
                    K Offline
                    kshegunov
                    Moderators
                    wrote on 13 Jan 2016, 21:03 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 13 Jan 2016, 22:07
                    0
                    • K kshegunov
                      13 Jan 2016, 21:03

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

                      A Offline
                      A Offline
                      ambershark
                      wrote on 13 Jan 2016, 22:07 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

                      K 1 Reply Last reply 14 Jan 2016, 19:22
                      0
                      • K Offline
                        K Offline
                        koahnig
                        wrote on 14 Jan 2016, 10:43 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
                          13 Jan 2016, 22:07

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

                          K Offline
                          K Offline
                          kshegunov
                          Moderators
                          wrote on 14 Jan 2016, 19:22 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 14 Jan 2016, 23:39
                          0
                          • K kshegunov
                            14 Jan 2016, 19:22

                            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 14 Jan 2016, 23:39 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
                            • K kshegunov
                              14 Jan 2016, 19:22

                              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 15 Jan 2016, 00:49 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

                              1/14

                              13 Jan 2016, 19:17

                              • Login

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