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

Signed-off-by: Shen-Ta Hsieh <ibmibmibm.tw@gmail.com>
This commit is contained in:
Shen-Ta Hsieh 2021-11-14 03:53:42 +08:00
parent a8c77a6fba
commit e783c2bd2c
No known key found for this signature in database
GPG Key ID: DF7FED2B0492FA77
2 changed files with 9 additions and 17 deletions

View File

@ -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());
} }

View File

@ -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:
*/ */
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()();
} }