If “store only what’s really necessary” is the goal, the one thing that absolutely must survive between calls is the engine (std::mt19937), because its internal state is what guarantees good randomness.
A distribution object is stateless with respect to the randomness; constructing a std::uniform_int_distribution every time is perfectly fine (it holds only two integers and a policy), but you can also keep it if you wish.
Two minimalist options:
──────────────────────────────────
- Keep only the generator (re-create the distribution each call)
// header: <random>
inline int throw_dice()
{
static std::mt19937 rng{ std::random_device{}() }; // ⚙️ built once
return std::uniform_int_distribution<int>{1, 6}(rng); // 🎲 1..6
}
• Only one long-lived object (rng).
• The distribution is a temporary; constructing it costs essentially nothing (two ints).
──────────────────────────────────
2. Keep both generator and distribution
inline int throw_dice()
{
static std::mt19937 rng { std::random_device{}() };
static std::uniform_int_distribution<int> dist(1, 6);
return dist(rng);
}
• A few extra bytes for dist, but zero construction cost after the first call.
──────────────────────────────────
Which one should I choose?
• If you roll many different ranges elsewhere (e.g. 1-100, 0-9, …) you might prefer #1, because each call makes its own distribution anyway.
• If this function always rolls 1-6, #2 is microscopically faster and still only keeps two tiny objects alive.
Either way you achieve:
• No global variables in user code.
• No per-call recreation of the expensive engine.
• Thread-local safety can be added by changing static → static thread_local if you roll dice from multiple threads.
That’s all you need to keep it lean and fast. Happy rolling! 🎲