复制构造函数初始化初始化列表中的引用成员会导致指针悬空
Copy constructor initialize a reference member in initialization list causes dangling pointer
我有一个带有引用成员的 A 类num
.我已经编写了一个复制构造函数,用于初始化列表中的num
。但结果似乎很奇怪,打印出来的值不应该是 100 吗?我的程序何时修改了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
该问题与复制构造函数无关。在构造函数A::A(int n)
中,您将成员引用num
绑定到构造函数参数n
,该参数在退出构造函数时将被销毁,使引用num
悬而未决。对它的任何取消引用都会导致 UB。
您可以将构造函数更改为接受引用,
A(int& n):num(n){}
然后像
int i = 100;
A a(i);
住
相关文章:
- 分段错误 - 读取初始化指针的数组
- 初始化指针的常量向量
- 初始化指针或引用成员变量以指向另一个成员
- C++初始化指针/引用/复制细微差别
- 使用无效指针初始化指针声明符的行为是否未定义?
- 在一行中初始化指针(新uint8_t[高度*宽度*3])
- 如何使用可变模板初始化指针?
- 初始化指针时出现写入访问冲突
- C 错误,带有卷曲括号的字面初始化指针
- 重新初始化指针是一种不好的做法吗?
- 初始化指针?C
- 初始化指针向量的向量
- 如何在类函数中正确初始化指针
- C++初始化指针会使应用程序随机崩溃
- 初始化指针结构 - 内存中的外观
- 如何使用struct构造函数在结构中初始化指针阵列
- 在一行中声明并初始化指针到类实例
- 分配数组与初始化指针
- QT 中的非初始化指针
- 使用地址值初始化指针