samedi 28 mars 2020

Singleton random generator class generates always the same sequence of integers

The RandomGenerator class is meant to provide a single instance of the generator to be used among different objects. The current implementation provides a getInstance method to get the single instance of the class and a getGenerator method that should provide the single instance of the generator also. The problem with this implementation is that the provided sequence of numbers is always the same on different PCs.

RandomGenerator.cpp

#include "RandomGenerator.h"

RandomGenerator::RandomGenerator() : generator(std::random_device()()) {}

RandomGenerator *RandomGenerator::getInstance() {
    std::call_once(inited, [&]{
        instance = new RandomGenerator();
    });
    return instance;
}

std::mt19937& RandomGenerator::getGenerator() {
    return generator;
}

RandomGenerator.h

#include <mutex>
#include <random>

class RandomGenerator {
private:

    inline static RandomGenerator* instance;
    inline static std::once_flag inited;
    std::mt19937 generator;

    RandomGenerator();
public:
    static RandomGenerator* getInstance();
    std::mt19937& getGenerator();
};



Aucun commentaire:

Enregistrer un commentaire