C ++ The difference between initializing a copy and initializing a constant reference if the value is obtained from a member variable

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;
};

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)?

+4
source share
2

. ( .. .)

-, :

const string myVal1 = myObj.getMyMember1();

const, myObj.

:

const string &myRef1 = myObj.getMyMember1();

const , myObj, .

... const promises , .

+4

, r-, r- , .

. : " rvalue , , rvalue".

. , , . , . , , RVO, .

+2

Source: https://habr.com/ru/post/1695782/


All Articles