我對TDM-GCC 4.6.1編譯器的右值引用做了一些實驗,並做了一些有趣的觀察,我無法用理論來解釋。我想請那裏的專家幫我解釋一下。右值引用基元整數是短命還是長命?
我有一個非常簡單的程序,不與對象,但INT原語處理和已定義的2個功能: foo1(返回由右值引用的局部變量)和 foo2的(返回由值的局部變量)
#include <iostream>
using namespace std;
int &&foo1();
int foo2();
int main()
{
int&& variable1 = foo1();
//cout << "My name is softwarelover." << endl;
cout << "variable1 is: " << variable1 << endl; // Prints 5.
cout << "variable1 is: " << variable1 << endl; // Prints 0.
int&& variable2 = foo2();
cout << "variable2 is: " << variable2 << endl; // Prints 5.
cout << "variable2 is still: " << variable2 << endl; // Still prints 5!
return 0;
}
int &&foo1() {
int a = 5;
return static_cast<int&&>(a);
}
int foo2() {
int a = 5;
return a;
}
似乎foo1返回的值和變量1接收到的值在一段時間後消失 - 也許是幾毫秒的短暫時間。請注意,我已經通過評論它禁止cout打印「我的名字是軟件愛好者」。如果我允許該聲明運行,結果會有所不同。看起來好像是因爲「cout < <」我的名字是softwarelover「引入的時間延遲。」5變爲0.
上面是如何rvalue引用應該在引用由函數返回的函數時引用的基本整數而不是按值返回嗎?爲什麼它是0,爲什麼不是垃圾?
另請注意,變量2從未出現無論我用cout打印多少次!variable2指的是一個函數返回值的原始整數,而不是通過引用的返回。
謝謝。
你怎麼知道0不是垃圾? –
我希望我們不會有這個錯誤接受的答案:http://stackoverflow.com/questions/9467872/addresses-and-lifetime-of-rvalue-references-or-of-xvalues-in-general –
永遠不會返回自動對象由右值引用。移動僅由移動構造函數執行,而不是由'std :: move'執行,而不是僅通過將右值綁定到右值引用。 [相關常見問題](http://stackoverflow.com/questions/3106110/) – fredoverflow