![](/img/trans.png)
[英]Initialize stringstream reference member in constructor initialization list with nothing
[英]Copy constructor initialize a reference member in initialization list causes dangling pointer
我有一個帶有參考成員num
A類。 而且我編寫了一個復制構造函數,用於在初始化列表中初始化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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.