修改引用的 int 时引发的特权指令异常

Privileged instruction exception thrown when modifying referred int

本文关键字:特权指令 异常 引用 int 修改      更新时间:2023-10-16

我一直在用常量和成员函数在C++做一些实验,我写了以下代码:

using namespace std;
#include <iostream>
class MyClass {
public:
    int& refToInt;
    MyClass(int x) : refToInt(x) { ; }
    void changeValue() const { refToInt++; }
};
int main() {
    int x = 10;
    MyClass mc(x);
    mc.changeValue();
    cout << mc.refToInt;
    return 0;
}

代码可以编译,但在执行时mc.changeValue();会引发异常:

Unhandled exception at 0x00AB1884 in tests.exe: 0xC0000096: Privileged instruction.

为什么我的代码会导致该异常?

在代码中,构造函数按值获取int参数(创建临时副本)。然后存储对该临时的引用(构造函数完成后,该引用将超出范围,因此您有一个悬而未决的引用)。然后,您的changeValue函数尝试通过该悬空引用更新长期死亡的临时值,从而导致未定义的行为和(在您的情况下(尽管编译器可以有效地执行任何操作))崩溃。