class A {
public:
string& getStr() {
return m_Str;
}
string m_Str;
};
int main() {
// Create a A object
A *a = new A();
a->m_Str = "abc";
// Get m_Str
string& s = a->getStr();
string s2 = a->getStr();
// Check the address
printf("%p\n%p\n%p\n", &s, &s2, &a->m_Str);
// Try to change something of m_Str
s[1] = 'd';
cout << a->getStr() << endl;
// Clear
delete a;
return 0;
}
Output:
0x7fa613c03450
0x7fff5e4a74d0
0x7fa613c03450
adc
Conclusion:
If you return a reference type from a method and you do not use a reference type to get the return value of this method. This will have a copy occurred.