static getter/setter



  • i need to have a static member in my class that will be assigned a value a few times during the program. i have a few ideas on how to do this but i'm not sure which is more correct. here's those ways:

    1. have a static member, and have a static method that'll return a reference to the static member
    2. have a static method that will create a static variable inside it and return a reference to it

    so which is more correct? or there's a better way? don't forget that i need to assign value to this. the reason i'm not sure which one to use is that if i use the 2nd option, is it appropriate to assign a value to function return value?

    thanks



  • IMHO solution 1 is better: you have a static member and static getter / setter. If you go with the second solution, then you're forced to use the same accessor for get / set, which might cause problem if you have a typo like if ( MyClass::myStaticGetter() = 8 ) instead of if ( MyClass::myStaticGetter() == 8 ).



  • @user4592357 said in static getter/setter:

    have a static method that will create a static variable inside it and return a reference to it

    Even if this is possible, I would not recomment to do this. The only place I have seen a pattern like this is for singleton, a la:

    static *Singleton::instance()
    {
      static Singleton *s = new Singleton;
      return s;
    }
    

    And what about option three: Having a static setter also? Therefore you encapsulate the access to your variable and can do sanity checks before the assignment also.

    And as you mentioned reference: if the size of your variable is <= 16 bytes, it may be more efficient to pass by value. If it is larger, pass by const reference.



  • @aha_1980

    good idea. but i don't need to do checks before assigning, should i still use static getter + static setter?

    it'll be a QString, so a reference or value?



  • @user4592357 said in static getter/setter:

    @aha_1980
    good idea. but i don't need to do checks before assigning, should i still use static getter + static setter?

    Isn't the reason to use classes that you can hide your data? And even if you don't need a check now, this can change in half a year. Further, it avoids the problems @JohanSolo mentioned.

    it'll be a QString, so a reference or value?

    In this case I'd use void mySetter(const QString &str); like all the Qt API do it.


Log in to reply
 

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