0

If I have the following function:

MyObject Process(std::string par1, int par2){
     MyObject message;
     // Do some processing here
    return message;
}

Can this be implemented like this:

MyObject Process(std::string par1, int par2){
         MyObject message;
         // Do some processing here
        return std::move(message);
    }

And what is the difference between both? (I have the notion that the second one will not copy the object message but just move it, but since message function scope is finishing, what does this represent?

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
  • 1
    You don't need to use `std::move` explicitly because of the implicit move rule. – Jason Jun 21 '22 at 10:18
  • @AnoopRana Does that mean that there is no difference and it is implicitly moved? I thought that returning it would copy the object to another object – KansaiRobot Jun 21 '22 at 10:18
  • Refer to the first [duplicate](https://stackoverflow.com/a/71934476/12002570) that i linked to your question where i have explained what will happen and why. Additionally check out [this](https://stackoverflow.com/questions/72383114/does-returning-a-local-variable-return-a-copy-and-destroy-the-original/72386932#72386932) which can also be helpful. – Jason Jun 21 '22 at 10:21
  • 2
    `std::move` can make it worse but never better. See https://en.cppreference.com/w/cpp/language/copy_elision – Goswin von Brederlow Jun 21 '22 at 10:24
  • 1
    @KansaiRobot - Moving does not magically teleport objects. All it does is affect overload resolution to determine how the target is initialized. In return statements there may be an implicit move, is all. (Well not quite *all*, a move or (N)RVO , which makes objects alias under the hood, thus avoiding more than one object.) – StoryTeller - Unslander Monica Jun 21 '22 at 10:28

0 Answers0