考慮我們有一個由值返回一個函數:參考R值(R值的地址)
int func() {
int x = 10; // create local variable x with value of 5
return x; // create temporary copy of x which is returned, local variable x is destroyed
}
int main()
{
int y = func(); // temporary copy of x is copied to y, when it hits`;` the temporary object is destroyed
return 0;
}
糾正我,如果我錯了的東西我在評論說以上。
現在我們可以通過持續引用它來延長臨時對象的生命週期。
int main()
{
const int & y = func(); // now the temporary object (R-value) is not destroyed when it hits `;` thus the life time is lenghtened.
return 0;
}
的問題是:既然我創建了一個恆定的參考應該被銷燬臨時對象,難道就因爲引用只不過是「別名」 cout << &y << endl
將打印的臨時對象的地址?還有那些存儲在內存中的臨時對象(R值)在哪裏(我使用原始類型int,但它可以是類)?
臨時存儲的地方不是你可以知道的。這是實現定義。 –
「存儲在內存中的那些臨時對象(R值)在哪裏?」爲什麼你甚至在意? – DimChtz
@JesperJuhl那麼打印'cout <<&y << endl;'的地址不是那個臨時對象的地址嗎?那麼這個地址代表什麼? – kvway