Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return lvalue reference from temporary object

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?

like image 799
barsan-md Avatar asked Jul 08 '15 22:07

barsan-md


People also ask

How do I return a temporary object in C++?

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.

Do functions return Rvalues?

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.

What is an lvalue reference?

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.

Can lvalue bind to rvalue reference?

An lvalue reference can bind to an lvalue, but not to an rvalue.


1 Answers

*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; }).

like image 157
StenSoft Avatar answered Oct 13 '22 23:10

StenSoft