LoginSignup
4
4

More than 5 years have passed since last update.

[C++] Method return a reference type

Last updated at Posted at 2016-06-07
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.

4
4
13

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4