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

parent a8c77a6f
...@@ -19,12 +19,10 @@ ...@@ -19,12 +19,10 @@
#include "LazyRandomEngine.hxx" #include "LazyRandomEngine.hxx"
void void LazyRandomEngine::AutoCreate() {
LazyRandomEngine::AutoCreate() if (engine)
{
if (engine != nullptr)
return; return;
std::random_device rd; std::random_device rd;
engine = new std::mt19937(rd()); engine.emplace(rd());
} }
...@@ -21,21 +21,19 @@ ...@@ -21,21 +21,19 @@
#define MPD_LAZY_RANDOM_ENGINE_HXX #define MPD_LAZY_RANDOM_ENGINE_HXX
#include <cassert> #include <cassert>
#include <optional>
#include <random> #include <random>
/** /**
* A random engine that will be created and seeded on demand. * A random engine that will be created and seeded on demand.
*/ */
class LazyRandomEngine { class LazyRandomEngine {
std::mt19937 *engine; std::optional<std::mt19937> engine;
public: public:
typedef std::mt19937::result_type result_type; typedef std::mt19937::result_type result_type;
LazyRandomEngine():engine(nullptr) {} LazyRandomEngine() : engine(std::nullopt) {}
~LazyRandomEngine() {
delete engine;
}
LazyRandomEngine(const LazyRandomEngine &other) = delete; LazyRandomEngine(const LazyRandomEngine &other) = delete;
LazyRandomEngine &operator=(const LazyRandomEngine &other) = delete; LazyRandomEngine &operator=(const LazyRandomEngine &other) = delete;
...@@ -46,16 +44,12 @@ public: ...@@ -46,16 +44,12 @@ public:
*/ */
void AutoCreate(); void AutoCreate();
static constexpr result_type min() { static constexpr result_type min() { return std::mt19937::min(); }
return std::mt19937::min();
}
static constexpr result_type max() { static constexpr result_type max() { return std::mt19937::max(); }
return std::mt19937::max();
}
result_type operator()() { result_type operator()() {
assert(engine != nullptr); assert(engine);
return engine->operator()(); 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