c++randompass-by-referenceclass-members

Default random engine as class member, even if passed by reference does not update external engine


I know that I have to pass the random engine by reference in order for it to update out of a function. However, if I pass it by reference in a class construction, it looks like the seed is not changing outside of the class.

Minimum working example:

#include<iostream>
#include<random>

class rv{
        public: 
        std::default_random_engine rv_eng;
        rv(std::default_random_engine & eng){
                this->rv_eng = eng;
        }
        double nd(){
                std::normal_distribution<double> ndist {0.0, 1.0};
                double draw = ndist(this->rv_eng);
                return draw;
        }
};

int main(){
        std::default_random_engine main_engine;
        main_engine.seed(123);
        std::cout << main_engine << std::endl;
        rv rv_instance(main_engine);
        std::cout << rv_instance.nd() << std::endl;
        std::cout << main_engine << std::endl;
        return 0;
}

The result I get is

123
-0.331232
123

While I would have expected the second generator to change. Why is it the same?


Solution

  • Like someone else already suggested; use an initializer list, that way you can have a reference variable as a member:

    class rv
    {
    public:
        std::default_random_engine& eng_ref;
        rv(std::default_random_engine& eng) : eng_ref{ eng } {};
        double nd()
        {
            std::normal_distribution<double> ndist {0.0, 1.0};
            double draw = ndist(eng_ref);
            return draw;
        }
    };