util/LazyRandomEngine: use std::optional to avoid allocation

parent a8c77a6f
......@@ -19,12 +19,10 @@
#include "LazyRandomEngine.hxx"
void
LazyRandomEngine::AutoCreate()
{
if (engine != nullptr)
void LazyRandomEngine::AutoCreate() {
if (engine)
return;
std::random_device rd;
engine = new std::mt19937(rd());
engine.emplace(rd());
}
......@@ -21,21 +21,19 @@
#define MPD_LAZY_RANDOM_ENGINE_HXX
#include <cassert>
#include <optional>
#include <random>
/**
* A random engine that will be created and seeded on demand.
*/
class LazyRandomEngine {
std::mt19937 *engine;
std::optional<std::mt19937> engine;
public:
typedef std::mt19937::result_type result_type;
LazyRandomEngine():engine(nullptr) {}
~LazyRandomEngine() {
delete engine;
}
LazyRandomEngine() : engine(std::nullopt) {}
LazyRandomEngine(const LazyRandomEngine &other) = delete;
LazyRandomEngine &operator=(const LazyRandomEngine &other) = delete;
......@@ -46,16 +44,12 @@ public:
*/
void AutoCreate();
static constexpr result_type min() {
return std::mt19937::min();
}
static constexpr result_type min() { return std::mt19937::min(); }
static constexpr result_type max() {
return std::mt19937::max();
}
static constexpr result_type max() { return std::mt19937::max(); }
result_type operator()() {
assert(engine != nullptr);
assert(engine);
return engine->operator()();
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment