Static local variables in bad practices?

there is something that overhears me.

In a non-stream program, is it better to have local static variables (inside methods) or static class members?

In this example:

class C{ public: C(){}; void foo(); }; void C::foo(){ static int bar = 0; bar++; printf("%d\n",bar); } 

Is this bad practice if bar will only be used in C::foo() ?

+8
c ++ variables static
source share
5 answers

Nothing is better. They serve a variety of uses.

+7
source share

I usually try to limit the scope of variables as much as possible, unless it becomes weird or tedious.

If you have 1000 lines of code in class C , including 100 lines of code in the foo function, any change you make to bar (for example, changing a name or type) requires going over 100 lines of code to make sure that the changes are okay. If you have bar static member of the class, you may have to move more than 1000 lines of code to make sure that bar is not used there. It will be a waste of time.

If you think you might need bar in another foo2 function (for example, when counting the number of calls for foo and foo2 together), you can make bar static member of the class.

+4
source share

If it is an open class, a static member of the class requires editing the header file. This is not always desirable.

Another option is a variable with file areas in an anonymous namespace. This is enough if you need access in only one way, and if you need it in several.

+2
source share

Object-oriented-speaking, bar is part of the state class C. This is the reason why I usually prefer to use fields rather than static local variables.

0
source share

Both local and nonlocal global variables are "bad" due to the fact that they are global. But the initialization and access are different for the two cases, so the answer you need to use depends on your needs regarding these requirements.

As an additional note, dynamic initialization of local variables with static storage duration may not be thread safe, depending on your compiler. The good news is that C ++ 0x guarantees that it will be thread safe.

0
source share

Source: https://habr.com/ru/post/650531/


All Articles