Coding Techniques
Static and Friend Members · Study material
Cache results in a function-local static
A static local container is created on the first call and shared by every later call, which makes it a simple, thread-safe-to-initialize cache for an expensive pure function.
#include <iostream>
#include <unordered_map>
class MathCache {
public:
static long long fib(int n) {
static std::unordered_map<int, long long> memo; // shared by all calls, created on first use
if (n < 2) return n;
if (auto it = memo.find(n); it != memo.end()) return it->second;
return memo[n] = fib(n - 1) + fib(n - 2);
}
};
int main() {
std::cout << MathCache::fib(50) << ' ' << MathCache::fib(60) << '\n'; // the second call reuses the cache
return 0;
}
12586269025 1548008755920
Write binary operators as hidden friends
class Rational {
int n_, d_;
public:
Rational(int n, int d = 1) : n_(n), d_(d) {}
// Member: only r + 2 works, 2 + r does not compile
// Rational operator+(const Rational& o) const;
// Hidden friend: r + 2 and 2 + r both work, found by ADL only
friend Rational operator+(const Rational& a, const Rational& b) {
return {a.n_ * b.d_ + b.n_ * a.d_, a.d_ * b.d_};
}
friend bool operator==(const Rational&, const Rational&) = default;
}; Prefer static inline and static constexpr (C++17)
// Before C++17: declaration in the header …
class Limits { public: static int max_users; static const double ratio; };
// … and a definition in exactly one .cpp file, or the linker complains
int Limits::max_users = 100;
const double Limits::ratio = 0.75;
// C++17: everything in the header, no separate definition
class Limits {
public:
static inline int max_users = 100;
static constexpr double ratio = 0.75;
}; Count instances correctly
class Tracked {
static inline int alive_ = 0;
public:
Tracked() { ++alive_; }
Tracked(const Tracked&) { ++alive_; } // copies are objects too!
Tracked(Tracked&&) { ++alive_; } // and so are moved-into objects
~Tracked() { --alive_; }
static int alive() { return alive_; }
};Forgetting the copy and move constructors is the classic bug: the compiler-generated ones do not touch your counter, so the count drifts negative.
Good static and friend habits
- Use
static inline/static constexprfor class-level data. - Prefer function-local statics to global objects (no initialization-order problems).
- Use static factory functions with expressive names instead of many constructor overloads.
- Make symmetric operators and
<</>>hidden friends. - Befriend the narrowest thing possible: one function rather than a whole class.
- Avoid mutable global state behind singletons; pass dependencies explicitly where you can.