【发布时间】:2019-05-31 06:16:27
【问题描述】:
#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;
}
这编译和运行 MSVC 没有问题。它使用gcc 编译没有错误,但mt19937 gen(rd()); 行导致程序崩溃并显示以下消息:
“myprog.exe 已停止工作
一个问题导致程序停止正常工作。如果有可用的解决方案,Windows 将关闭该程序并通知您。”
有什么想法吗?
gcc 命令:g++ mycode.cpp -fpermissive -s -o myprog.exe
更新:
在编译命令中添加-O2 可以让程序运行,尽管运行不正确。 “随机”函数不再是随机的;它总是返回 1。例如,使用以下“主”代码进行测试...
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;
}
...产生此输出:<0, 1000>
【问题讨论】:
-
能否分享崩溃信息?
-
我在 wandbox.org 中尝试了多个 GCC 版本——没有崩溃
-
@TheQuantumPhysicist myprog.exe 已停止工作 一个问题导致程序停止正常工作。如果有可用的解决方案,Windows 将关闭该程序并通知您。
-
请注意,GCC 在 Windows 上一直存在
std::random_device的问题 - 它可能总是产生相同的非随机数。您使用的是哪个 GCC 版本号? -
旁注:您可能不需要或不想在每次调用
randomBit时重新设置随机数生成器的种子