修改引用的 int 时引发的特权指令异常
Privileged instruction exception thrown when modifying referred int
我一直在用常量和成员函数在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
函数尝试通过该悬空引用更新长期死亡的临时值,从而导致未定义的行为和(在您的情况下(尽管编译器可以有效地执行任何操作))崩溃。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- C++中的赋值发生,尽管右侧出现异常
- C++:对不存在的命名空间使用命名空间指令
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 函数名是c中该函数的第一条指令的地址吗
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 稍后在构造函数中重新启动异常指令删除此指令
- 修改引用的 int 时引发的特权指令异常
- strcpy() 上的特权指令运行时错误
- 异常不会中断指令流