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?
No, the former
auto &r1 = a.func1();isn't legal/valid C++ sincefunc1returns 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:And this won't work as a non-const lvalue reference can't be bound to an rvalue.