3
對this question的回答指出,不應該返回對參數的引用,因爲它們可能是超出範圍的臨時對象,並且如果將結果分配給引用,則不會保留。C++:對參數的引用
遵循這個邏輯,下面的code有沒有類似的問題?
#include <iostream>
class T
{
public:
T& operator+=(const T& t) { this->x += t.x; return *this; }
T(int x) : x(x) {}
int x;
~T()
{
std::cout << "My value is " << this->x << " and I'm dead." << std::endl;
this->x = -999;
}
};
int main()
{
const T& t = (T(2) += T(3));
std::cout << t.x << std::endl;
}
如果是這樣,我應該怎麼寫+=
操作來避免這個問題?
我也想象會出現在C++ 11下面的代碼的問題,但我沒有檢查它:
#include <iostream>
#include <string>
int main()
{
for (char x : std::string("hello") += std::string("world"))
{
std::cout << x << std::endl;
}
}
這似乎是你永遠不應該返回引用的功能參數結果,除非您準備在基於循環的範圍內冒未定義的行爲。
'auto &&'會綁定一個左值引用,因爲那是'operator + ='返回的值。這不會延長臨時的生命週期,而且代碼確實是未定義的行爲。 – 2012-02-29 09:06:40
@ R.MartinhoFernandes:的確,我的錯誤。 – 2012-02-29 09:13:17