util/LazyRandomEngine: use std::optional to avoid allocation
Signed-off-by: Shen-Ta Hsieh <ibmibmibm.tw@gmail.com>
This commit is contained in:
parent
a8c77a6fba
commit
e783c2bd2c
@ -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()();
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user