I surfed on the internet and found different ways of counting a number in every function call.
1. Using Functor
class count_number {
private:
int number;
public:
count_number(): number{1} {}
void operator()() {
std::cout << "Number " << number++ << '\n';
}
};
...
count_number counter;
counter();
counter();
counter();
Outputs:
Number 1
Number 2
Number 3
2. Using Lambda
They said they resemble functors and the only difference is their mutability.
...
// Prior to C++ 23:
auto counter = [number = 1]() mutable { std::cout << "Number " << number++ << '\n'; };
counter();
counter();
counter();
Outputs exactly the same as above.
3. Using Static Variable
The variable number
persists in every function call.
void counter() {
static int number = 1;
std::cout << "Number " << number++ << '\n';
}
...
counter();
counter();
counter();
Which still outputs exactly the same.
The questions are:
- What are the pros and cons of the three ways in terms of memory efficiency, performance, and readability.
- Which one do you think is the best and why? If none, what is it?
- What's the point of having static variables inside a function aside from persisting data?