![](/img/trans.png)
[英]Is the lvalue reference return of a member function of a temporary object a dangling reference?
[英]Return lvalue reference from temporary object
是,返回左值引用*this
,允許*this
是一個右值?
#include <iostream>
#include <string>
using namespace std;
class A {
public:
A& f() {
return *this;
}
string val() const {
return "works";
}
};
int main() {
cout << A{}.f().val();
}
是否有任何情況, f()
返回的值在某個時刻會成為懸空參考?
調用f()
是否會延長調用者的生命周期(如果這是示例中的右值)?
*this
絕不是右值,但在這種情況下,它是(參考)臨時的。 臨時數據是有效的對象,直到它們被定義的語句完成,即直到代碼到達終止;
,或直到for
, if
, while
, do
和switch
語句的控制表達式結束,例如if (A{}.f()) { something; }
if (A{}.f()) { something; }
,臨時有效直到最后一個)
在條件體( { something; }
)之前。
*this
不是右值。 這是一個左值。
所以,沒問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.