提问人:user2589743 提问时间:9/6/2019 最后编辑:songyuanyaouser2589743 更新时间:9/6/2019 访问量:220
复制构造函数初始化列表中的引用成员会导致指针悬空
Copy constructor initialize a reference member in initialization list causes dangling pointer
问:
我有一个带有引用成员的 A 类。我编写了一个在初始化列表中初始化的复制构造函数。但结果似乎很奇怪,打印出来的值不应该是 100 吗?我的程序什么时候修改了 和 的值?num
num
a.num
aa.num
#include <iostream>
using namespace std;
class A{
public:
int& num;
A(int n):num(n){}
A(const A& obj):num(obj.num){}
void print(){
cout << num << endl;
}
};
int main(){
A a(100);
A aa = a;
a.print(); //Expected to be 100, but it isn't
aa.print(); //Also expected to be 100, but it isn't
//The address of a.num and aa.num are the same, so both of them are referencing to the same place. But the question is why the value isn't 100 but a strange value
cout << &(a.num) << " " << &(aa.num) <<endl;
}
输出为:
-1077613148
-1077613148
0xbfc4ed94 0xbfc4ed94
答:
5赞
songyuanyao
9/6/2019
#1
该问题与复制构造函数无关。在构造函数中,您将成员引用绑定到构造函数参数,当离开构造函数时,该参数将被销毁,使引用悬空。对它的任何取消引用都会导致 UB。A::A(int n)
num
n
num
您可以将构造函数更改为获取引用,
A(int& n):num(n){}
然后像这样使用它
int i = 100;
A a(i);
评论
0赞
user2589743
9/6/2019
哇,你是天才!这解决了我的问题!非常感谢
评论