C++ 在类成员"无符号长"上使用"^="和"<<"时出现总线错误

C++ Bus error when using `^=` and `<<` on a class member `unsigned long`

本文关键字:lt 错误 总线 成员 无符号 C++      更新时间:2023-10-16

我试图实现这个答案中定义的随机数生成器。至少据我所知,关于第一行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();