C++ 在类成员"无符号长"上使用"^="和"<<"时出现总线错误
C++ Bus error when using `^=` and `<<` on a class member `unsigned long`
我试图实现这个答案中定义的随机数生成器。至少据我所知,关于第一行static unsigned long x=123456789, y=362436069, z=521288629;
应该如何实现,存在一些歧义,因为它显示在函数之外。我假定它打算作为类成员,并这样实现它:
class rng2{
public:
unsigned long x, y, z;
rng2() : x(123456789), y(362436069), z(521288629) {}
unsigned long xorshf96(void) { //period 2^96-1
//static unsigned long x=123456789, y=362436069, z=521288629;
unsigned long t;
x ^= x << 16; //BUS ERROR, debug mode
x ^= x >> 5;
x ^= x << 1;
t = x;
x = y; //SEG FAULT, release mode
y = z;
z = t ^ x ^ y;
return z;
}
};
int main ()
{
rng2 rand2;
rng2 * prand;
for(long d =0; d < 10000; d++)
cout << "n" << (*prand).xorshf96();
}
由于某种原因,这会在指定的位置产生错误,这取决于我使用的编译模式。但是,如果我注释掉成员变量和构造函数并使用静态变量,一切都可以正常工作。如果这是正确的代码,我不明白为什么它在链接上显示不同,无论哪种方式,我都不知道为什么会发生错误。
您正在使用*prand,但没有初始化prand
rng2 * prand;
你完全确定这是真正的代码吗?考虑到您没有初始化该指针并稍后对其解引用,因此错误非常明显。
prand
是一个野指针。
改变:
int main ()
{
rng2 rand2;
rng2 * prand;
for(long d =0; d < 10000; d++)
cout << "n" << (*prand).xorshf96();
}
:
int main ()
{
rng2 rand2;
rng2 * prand = &rand2;
for(long d =0; d < 10000; d++)
cout << "n" << (*prand).xorshf96();
}
或者直接写
int main ()
{
rng2 rand2;
for(long d =0; d < 10000; d++)
cout << "n" << rand2.xorshf96();
}
这是因为prand
指针从来没有被分配,只是被使用。当使用static
时,访问变量no数据成员,这就是为什么您不会得到总线错误。应该在主函数中明确地为指针赋一个有效值。这样的
rng2 * prand = new rng2();
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- &lt;&lt;操作员在C 中超载错误
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- '&lt;'''&lt;'''&quot的模板类错误''令牌”
- 在尝试超载&lt;&lt;时链接错误2005和1169操作员
- 错误:没有匹配'运算符<<"在'std::cout
- 过载<<比如cout错误
- 重载& lt; & lt;为什么我得到以下错误
- 重载ostream&时转换错误无效;operator< & lt;
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多
- 编译器错误,包括'<'代币
- 重载& lt; & lt;错误