|
There are many reasons why global variables are bad, but extremely high on the list (if not first) is concurrency issues. The fact that the author think it's acceptable in any C or C++ code base to put in code like: static int prv_counter;
int counter() { return ++prv_counter; }
Is insanity. Like, this is programmer malpractice. This function can only ever be called from one thread (not to mention: using `int` instead of `int64_t` is also a trivial mistake, this easily overflows). This is the kind of thing that enters a code base, works fine for long enough that everyone forgets about it, then causes horrible security issues and crashes. The idea of saying this is "good use" of a global variable is... this person should not be giving advice on good coding.If you want to do this (and you shouldn't, because global state is bad for 14 other reasons), at the very least, make it thread safe and not trivially overflowing: static std::atomic<int64_t> prv_counter { 0 };
int64_t counter() { return 1 + prv_counter.fetch_add(1, std::memory_order_relaxed); }
(the 1+ is because the original author used pre-increment instead of post-increment)Like, this is not awesome, and you shouldn't do it, but it's at least not a total disaster. EDIT: actually, this is also bad, because the `prv_counter` is not really private at all. The better way to do that would be: int64_t counter() {
static std::atomic<int64_t> prv_counter { 0 };
return 1 + prv_counter.fetch_add(1, std::memory_order_relaxed);
}
Three different serious issues in two lines of code, fun! |
The point is that there is no solution that works for all use cases. If you always attempt to write fully generalized code like that you'll end up with tons of unnecessary complexity. Solve the problem at hand, not some hypothetical.
The author even specifies a rule that covers your case:
"If you're using threads, global and static variables should be thread local. If they are not then the discussion becomes about sharing data across threads and synchronization, which is a different topic."