barsdeveloper
barsdeveloper

Reputation: 960

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?

Upvotes: 8

Views: 840

Answers (2)

StenSoft
StenSoft

Reputation: 9609

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

Upvotes: 10

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385114

*this is not an rvalue. It is an lvalue.

So, no problem.

Upvotes: -2

Related Questions