Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/164.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
修改引用的int时引发特权指令异常 我已经用C++和成员函数做了一些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; }_C++_Exception - Fatal编程技术网

修改引用的int时引发特权指令异常 我已经用C++和成员函数做了一些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; }

修改引用的int时引发特权指令异常 我已经用C++和成员函数做了一些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; },c++,exception,C++,Exception,为什么我的代码会导致这种异常?在您的代码中,构造函数按值获取一个int参数(这将创建一个临时副本)。然后存储对该临时对象的引用(一旦构造函数完成,该临时对象就超出范围,因此有一个悬空引用)。 然后,您的changeValue函数尝试通过该悬空引用更新长期失效的临时值,导致未定义的行为和(在您的情况下(尽管编译器可以有效地执行任何操作))崩溃。MyClass构造函数的参数就像一个局部变量,因此,当构造函数主体返回时,它将超出范围。现在猜猜refToInt将引用什么。。。请改为尝试通过引用传递参数。

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

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

MyClass构造函数的参数就像一个局部变量,因此,当构造函数主体返回时,它将超出范围。现在猜猜
refToInt
将引用什么。。。请改为尝试通过引用传递参数。由于使用悬挂引用而导致行为未定义。作为成员引用通常不是一个好主意。这与恒量无关。。有了正确的标志,它甚至应该拒绝编译。
Unhandled exception at 0x00AB1884 in tests.exe: 0xC0000096: Privileged instruction.