Consider the following:
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass(string myMemberInitValue);
const string getMyMember1();
private:
string myMember;
};
MyClass::MyClass(string myMemberInitValue) :
myMember(myMemberInitValue)
{}
const string MyClass::getMyMember1()
{
return myMember;
}
int main()
{
MyClass myObj("Hello World");
const string myVal1 = myObj.getMyMember1(); // Ok
const string &myRef1 = myObj.getMyMember1(); // A reference to an rvalue
...
return 0;
};
Normally if you use a constant reference to a r-value the lifetime of the r-value is extended to match the lifetime of the reference...
1. But what if the r-value is a member variable of an object?
Either the value gets copied or a reference to the member variable is made but that would just be valid as long as the value of the member variable doesn't change...
2. So in my understanding the value must be copied anyway, right?
3. So is there a difference between const string myVal1 = myObj.getMyMember1()
and const string &myRef1 = myObj.getMyMember1()
(compiler behavior, performance)?