vendredi 5 juin 2015

In the code below, RandomCharSource is supposed to simply return a random character upon request. Its constructor is initializing an mt19937, uniform_int_distribution<int> and a random_device. However, when I instantiate my object, I get a segfault.

When I create these random classes manually in the bar() function below, it works fine.

What am I doing wrong? Is there an initialization order issue here? I'm using GCC 4.7.3.

#include <random>
#include <iostream>

class RandomCharSource
{
public:
    explicit RandomCharSource() : _re{_rd()}, _dist{0, 255} {};
    inline char get_next_char() { return _dist(_re); };
private:
    std::mt19937 _re;
    std::uniform_int_distribution<int> _dist;
    std::random_device _rd;
};

void foo()
{
    RandomCharSource s;
    std::cout << s.get_next_char() << std::endl;
}

void bar()
{
    std::random_device _rd;
    std::mt19937 _re{_rd()};
    std::uniform_int_distribution<int> _dist{0,255};
    std::cout << (char)_dist(_re) << std::endl;
}

int main()
{
    bar(); // Works OK
    foo(); // Segfault

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire