there is something that's bugging me.
In a non-threaded 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 it considered a bad practice if bar
will solely be used in C::foo()
?
Are static local variables bad practice? No. Static local variables differ in exactly one regard to non-local private variables: they have a smaller scope. Since you always want to keep scope as small as possible (= better encapsulation), local statics can be advantageous over private variables.
Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.
Local variables are stored in each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe.
When applied to a local variable, the static keyword defines the local variable as having static duration, meaning the variable will only be created once, and will not be destroyed until the end of the program.
Neither is better. They serve very different use cases
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With