Is, returning an lvalue reference to *this
, allowed when *this
is an rvalue?
#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();
}
Is there ANY scenario where the value returned by f()
will be a dangling reference at some point?
Does calling f()
prolongs the lifetime of the caller if this is an rvalue like in example?
If you change the return type to const char * and return ss. str(). c_str() you would return pointer to some buffer of temporary std::string returned by ss.
Typically rvalues are temporary objects that exist on the stack as the result of a function call or other operation. Returning a value from a function will turn that value into an rvalue. Once you call return on an object, the name of the object does not exist anymore (it goes out of scope), so it becomes an rvalue.
An lvalue is an expression that yields an object reference, such as a variable name, an array subscript reference, a dereferenced pointer, or a function call that returns a reference. An lvalue always has a defined region of storage, so you can take its address.
An lvalue reference can bind to an lvalue, but not to an rvalue.
*this
is never an rvalue but in this case, it is (a reference to) a temporary. Temporaries are valid objects until the statement where they are defined is completed, i.e. until the code reaches the terminating ;
, or until the end of the controlling expression for for
, if
, while
, do
, and switch
statements, e.g. in if (A{}.f()) { something; }
, the temporary is valid until the last )
before the body of the condition ({ something; }
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With