Global string variable



  • How I can declare string global variable in head module?

    For example for int i use
    public:
    static int value;

    And what about string????



  • Hi!

    nix.h :

    #ifndef NIX_H
    #define NIX_H
    
    #include <QString>
    
    class Nix
    {
    public:
        static QString str;
    };
    
    #endif // NIX_H
    

    nix.cpp :

    #include "nix.h"
    
    QString Nix::str;
    


  • That works, but is somewhat dangerous because you don't know exactly when the string is destructed.

    If, for some reason, you access the string after it has already been destroyed (typically in the destructor of another static object), you are dead. Well, your application is.

    The alternative is a bit more complex:

    1. Create a pointer-to-QString and initialize it with NULL
    2. Create a static getter method that initializes the QString if NULL, then returns the pointer or a reference

    Now all you have to worry is that two threads call the method at the same time, thus creating two instances for the string. The easiest way to prevent this is by using the function within the static initialization of another variable, forcing it to run before main() starts, and while there is still only one thread.

    The whole might look like this:
    Within nix.h:

    static QString* str;
    static const bool bStrInitialized;
    static QString& getStr();
    

    Within nix.cpp:

    QString* Nix::str = NULL;
    const bool Nix::bStrInitialized =(&Nix::getStr() != NULL);
    
    const QString& Nix::getStr()
    {
       if (str == NULL)
       {
          str = new QString;
       }
       return *str;
    }
    


  • @Asperamanca said:

    That works, but is somewhat dangerous because you don't know exactly when the string is destructed.

    The string is global and thus destroyed by the runtime when the process stopped execution.


  • Moderators

    @Asperamanca said:

    That works, but is somewhat dangerous because you don't know exactly when the string is destructed.

    Only when you use in another global object I guess. Never came across such an issue yet. Faced while constructing though.



  • @Wieland said:

    @Asperamanca said:

    That works, but is somewhat dangerous because you don't know exactly when the string is destructed.

    The string is global and thus destroyed by the runtime when the process stopped execution.

    Yes, but if you have multiple static objects, in which order will they destruct? We had a case where a logging function used a static object. Someone called the logging function in a destructor. And someone else used that class as a static object. Then we had to pick up the pieces.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.