static variable vs. member

前端 未结 3 1192
轻奢々
轻奢々 2021-02-07 17:25

If you have data for a class that will be modified and needs to be retained throughout the program, but is only used in one member function, is it preferred to make that variabl

相关标签:
3条回答
  • 2021-02-07 17:48

    The question isn't "will the data be used throughout the program", but rather "if you make two objects of this class, do you want them to share this data?" If yes, make it static. If no, don't.

    0 讨论(0)
  • 2021-02-07 17:55

    Declaring a local variable as static means your method now has state, separate from the object's state. It can lead to many mistakes when maintaining this code (such as copy constructor implementation, assignment, serialization) and when reading it (unclear method behavior).
    Avoid using static locals unless you have some good reason (the only one I can think of is single threaded singletone implementation).

    0 讨论(0)
  • 2021-02-07 17:58

    I would argue that in most cases, you should never use a local static variable, and instead use a static member variable. Then the question degenerates to if that variable should be shared among the class instances or not.

    0 讨论(0)
提交回复
热议问题