Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to return an object from a C++ function?

I am confused between :

  • returning an object (but then the object is copied from the local variable in the function, which consumes memory)
  • returning a pointer (but then you have to remember to delete it, in the calling code, which is weird)
  • returning a reference (but this is not possible because this would be a reference to a local variable of the function, which would be deleted as soon as the function ends)

I am looking for the proper way to return an object from a C++ function, in basic C++ (no library handling pointers and freeing memory automatically). I want to know how this is supposed to be done.

Thank you

like image 325
Matthieu Napoli Avatar asked Dec 03 '22 11:12

Matthieu Napoli


2 Answers

Modern compilers typically implement the (Named) Return Value Optimization, by which the copy you reference (and would logically expect) is not done.

Ever since Visual Studio 2005 (VC++ 8.0) I don't think twice about returning objects.

like image 161
Steve Townsend Avatar answered Jan 04 '23 23:01

Steve Townsend


What about std::auto_ptr from <memory>? Or if C++0x is concerned std::unique_ptr?

like image 25
Armen Tsirunyan Avatar answered Jan 04 '23 22:01

Armen Tsirunyan