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();
const string &myRef1 = myObj.getMyMember1();
...
return 0;
};
Usually, if you use a constant reference to an r-value , the lifetime of the r-value extends to match the lifetime of the link ...
1. But what if the r-value is a member variable of an object?
Either the value is copied, or a reference is made to the member variable, but this will be true only if the value of the member variable does not change ...
2. So, in my understanding, the value should be copied anyway, right?
3. That is, the difference between const string myVal1 = myObj.getMyMember1()and const string &myRef1 = myObj.getMyMember1()(compiler behavior, performance)?
source
share