mercredi 7 octobre 2015

pointer to other class (boost::variate_generator) not work

I'm trying to generate random numbers using boost/random.hpp, I'd like to fix the seed at initialization, and call getRandom() to generate random numbers according to the seed. But this code doesn't work:

class A 
{
public:
    A() 
    {
        unsigned long seed =12411;
        boost::mt19937 rng(seed);
        boost::normal_distribution<> norm(0.0, 1.0);  
        boost::variate_generator<boost::mt19937&,
                                 boost::normal_distribution<> > 
        randNorm(rng, norm);
        randPtr = &randNorm;
        //(*randPtr)();
        std::cout << (*randPtr)() << std::endl;
    }
    double getRandom() 
    {
        return (*randPtr)();
    }        
private:
    boost::variate_generator<boost::mt19937&,
                             boost::normal_distribution<> >* 
    randPtr;

};
int main() {
    A a;
    std::cout << a.getRandom() << std::endl;
}

For the above code, it can compile, will print one random number (called in the constructor), then Segmentation fault: 11. So the pointer randPtr only works inside the constructor. Could anyone give me any suggestion on this? Thank you!




Aucun commentaire:

Enregistrer un commentaire