drbombe
drbombe

Reputation: 639

Passing random engine through a function - why different compiler behaves differently

For your convenient to illustrate this issue, I made the minimalist codes as below. The codes look innocent but the results are surprising! I tried on different compiler on my Mac and PC. The gcc seems fine but the clang provides incorrect results. My guess is that it may be some undefined behavior. The Mac results show repeat pattern of non-random number. Why this happens?

Here are the codes

#include <iostream>
#include<random>
using namespace std;

class FillUpX{
public:
    FillUpX(default_random_engine eng):generator{eng}{};
    void printValue(){
        for(int i=0;i<10;++i){
            cout << rnorm(generator) << endl;
        }
    }

private:
    default_random_engine & generator;
    std::normal_distribution<> rnorm{0,1};
};


int main(){

    unsigned seed=10;
    std::default_random_engine gen{seed};


    FillUpX fhd(gen);
    fhd.printValue();

   return 0;
}

Here are the outputs

-0.361197
1.67039
-0.361197
1.67039
-0.361197
1.67039
-0.361197
1.67039
-0.361197
1.67039

Upvotes: 1

Views: 74

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

The problem is in your constructor:

FillUpX(default_random_engine eng):generator{eng}{};

You take the engine by value and then save a reference to it. That object will of course be destructed once the constructor returns, making your reference invalid.

Upvotes: 4

Related Questions