Does it work when a reference refers to a function's return value?

129 views Asked by At
class AA {
private:
    string s = "asd";
public:
    string func1() {
        return s;
    }
    string& func2() {
        return s;
    }
};

func1() returns a copy and func2() returns a reference. And calls are like

AA a;
auto &r1 = a.func1();
auto &r2 = a.func2();

Both work fine after I test them. But here is my doubt. r2 refers to AA::s; I get it. But does r1 refer to AA::s too? Or func1's anonymous return value? If the former, how does func1 do it? RVO?

1

There are 1 answers

0
user12002570 On

Both work fine after I test them

No, the former auto &r1 = a.func1(); isn't legal/valid C++ since func1 returns by value and since placeholder type deduction uses the rules for template argument deduction. This means that the situation/problem is similar to the problem as if you were to write:

template<typename T> void deducefromauto(T &t);
deducefromauto(a.func1()); //won't work because non-const lvalue reference can't be bound to rvalue

And this won't work as a non-const lvalue reference can't be bound to an rvalue.