c++ - Return lvalue reference from temporary object -
is, returning lvalue reference *this, allowed when *this rvalue?
#include <iostream> #include <string> using namespace std; class { public: a& f() { return *this; } string val() const { return "works"; } }; int main() { cout << a{}.f().val(); } is there scenario value returned f() dangling reference @ point?
does calling f() prolongs lifetime of caller if rvalue in example?
*this never rvalue in case, (a reference to) temporary. temporaries valid objects until statement defined completed, i.e. until code reaches terminating ;, or until end of controlling expression for, if, while, do, , switch statements, e.g. in if (a{}.f()) { something; }, temporary valid until last ) before body of condition ({ something; }).
Comments
Post a Comment