How to “return an object” in C++?

后端 未结 8 648
礼貌的吻别
礼貌的吻别 2020-11-22 09:25

I know the title sounds familiar as there are many similar questions, but I\'m asking for a different aspect of the problem (I know the difference between having things on t

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 09:37

    Just return a object like this:

    Thing calculateThing() 
    {
       Thing thing();
       // do calculations and modify thing
       return thing;
    }
    

    This will invoke the copy constructor on Things, so you might want to do your own implementation of that. Like this:

    Thing(const Thing& aThing) {}
    

    This might perform a little slower, but it might not be an issue at all.

    Update

    The compiler will probably optimize the call to the copy constructor, so there will be no extra overhead. (Like dreamlax pointed out in the comment).

提交回复
热议问题