C ++: returning by value using a link

I am trying to figure out what exactly happens when you return an object reference in a function with the type of the returned object.

Consider the following function:

CObject getObject() {
    CObject localObject;
    CObject &objectRef(localObject);
    return objectRef;
}

I understand that this function will return a copy of "localObject", and will not return a link to "localObject". It's right? Is this essentially creating and returning a new object with localObject as the constructor parameter? For instance,

CObject newObject(localObject);
+4
source share
2 answers

It will return a copy of your object. However, be careful if you modify the function declaration to return a link, your code will result in Undefined Behavior.

Example:

class CObject{
    public:
    CObject(){std::cout << "cosntructing ";}
    CObject(const CObject& other){std::cout << "copying ";}
};

CObject getObject(){
    CObject localObject;
    CObject &objectRef(localObject);
    return objectRef;
}

int main(){
   auto result =  getObject();
}

This will lead to:

cosntructing copy

: , - RVO. . @Caduchon , - -.


undefined :

CObject& getObject() {
    CObject localObject;
    CObject &objectRef(localObject);
    return objectRef;
}
+6

, . , , . - - , CObject . , , localObject , , .

+1

All Articles