#include <iostream>
#include <random>
using namespace std;
class myclass
{
private:
static bool randomBit()
{
std::random_device rd; // Obtain a random seed number from hardware
std::mt19937 gen(rd()); // Initialize and seed the generator <---- CRASH!!
uniform_int_distribution<> distr(0, 1); // Define the distribution range
return distr(gen);
}
myclass::myclass() = delete; // Disallow creating an instance of this object
public:
static bool generateRandomBit()
{
return randomBit();
}
};
int main()
{
cout<<myclass::generateRandomBit()<<endl;
return 0;
}
This compiles and runs without problems with MSVC. It compiles without errors with gcc
but the mt19937 gen(rd());
line causes the program to crash with the following message:
"myprog.exe has stopped working
A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available."
Any ideas?
gcc command: g++ mycode.cpp -fpermissive -s -o myprog.exe
UPDATE:
Adding -O2
to the compiling command gets the program to run, albeit incorrectly so. The "random" function is no longer random; it always returns 1. For example, testing with the following "main" code...
int main()
{
int a[2] {0, 0};
for (int i = 0; i < 1000; i++) {
a[myclass::generateRandomBit()]++;
}
cout<<"<"<<a[0]<<", "<<a[1]<<">"<<endl;
return 0;
}
...yields this output: <0, 1000>