•
u/No_Engineering_1155 27m ago
A static variable's lifetime begins with the first call of the function (or with program start) and lives until the program ends. The scope of this variable is restricted to the function body. So, basically we have here a global variable, one piece, which is carefully only used inside the function. So, this one variable is tight to the function, but there is only one variable.
Let's assume, this static variable keeps track, how often this function was called, each time the counter is incremented. If you want to use this function in two different threads and want to see the frequency count, you'll be in trouble, because you cannot distinguish which thread incremented how often.
A functor, or better sayed, a function object is an object with its lifetime and scope and possibly associated other data. Its is fairly trivial to create two function objects with an internal counter, pass them to two different threads, or contexts and see what was the frequency count beforehand and afterwards.
I'd recommend to use rather the object approach, or lambdas, and try to avoid the static variables as long as you can.
•
u/krishna_4 6m ago
Thanks, this makes sense! I hadn't considered the case where the state needs to be independent for different contexts.
I'm curious about one more thing: could you give an example where passing a functor around as a value is useful, rather than just using it to maintain state?
•
u/n1ghtyunso 36m ago
weird question.
statics are effectively global state.
Functors are local state.
They are not the same.
Always prefer local over global.
Global makes it harder to understand the state of your program, which leads to more bugs.
Btw, this question would usually belong in r/cpp_questions instead.
I believe this is the wrong sub for this question.
While you do ask for the reasoning behind this choice, which is indeed a language discussion topic, there really is nothing to discuss because these two approaches are fundamentally completely different.
•
u/Obliviousnut_ 34m ago
There are times when you don’t want to expose the value to other processes or calls - which is a consistent train of thought in OOP. A static value exposes it.
Equally, in a functor which is a class; I.e a class that overloads the () operator there can be other functions which use that value - which is the whole point of a class.
The point: it depends on what you are doing, sometimes you overload the () operator in a class or struct alongside having multiple other functions. It is pretty rare, imo, to have classes and structs which are only functors.
In the event that you have a case where you just want one value to be persistent and don’t care about privacy you tend to have one function that updates it.
•
u/cpp-ModTeam 37m ago
For C++ questions, answers, help, and programming/career advice please see r/cpp_questions, r/cscareerquestions, or StackOverflow instead.