你能告訴我爲什麼在不同編譯器中類的引用成員的輸出是不同的?
類參考成員列表初始化
class B
{
int& aRef;
public:
B(int c):aRef(c){}
void Print()
{
cout<<aRef<<endl;
}
};
void f(int s)
{
int& lcRef=s;
cout<<lcRef<<endl;
}
int main()
{
int x=100;
B s(x);
s.Print(); //ms c++ output : 3323244, gcc output :100
f(x); //ms c++ output : 100, gcc output:100
return 0;
}
和功能f(int s)
秒問題參數的行爲相同的邏輯,B類的初始化的構造器?
你保存參考到一個臨時(了'INT c'parameter到'B'構造函數)。一旦構造函數完成,它不再處於範圍內,被銷燬,然後你有一個懸而未決的參考。之後訪問它是**未定義的行爲**。 – WhozCraig