从临时对象返回左值引用

时间:2015-07-08 22:17:48

标签: c++ reference lifetime lvalue rvalue

是否,在import MapKit class LocationA { let name: String let identifier: String let latitude: CLLocationDegrees let longitude: CLLocationDegrees init (name: String, identifier: String, latitude: CLLocationDegrees, longitude: CLLocationDegrees) { self.name = name self.identifier = identifier self.latitude = latitude self.longitude = longitude } } 为右值时允许将左值引用返回import MapKit extension LocationA: MKAnnotation, NSObject { var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } var title: String! { return identifier } var subtitle: String! { return name } }

*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(); } 会延长调用者的生命周期吗?

2 个答案:

答案 0 :(得分:9)

*this永远不是右值,但在这种情况下,它是(引用)临时值。 Temporaries是有效的对象,直到它们被定义的语句完成,即直到代码到达终止;,或直到for的控制表达式结束,if,{{ 1}},whiledo语句,例如在switch中,临时有效,直到条件正文(if (A{}.f()) { something; })之前的最后)

答案 1 :(得分:-2)

button { font-size: 14px; height: 25px; width: 25px; text-align: center; vertical-align: middle; padding: 0; margin-left: auto; margin-right: auto; } 不是左值。这是一个左值。

所以,没问题。

相关问题