Reputation: 49533
I am confused between :
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
Upvotes: 5
Views: 2643
Reputation: 6342
returning an object (but then the object is copied from the local variable in the function, which consumes memory)
Optimal compilers may not take significant time to create copy. You may also need to implement copy constructor and overload assignment operator, depending upon your object contents.
returning a pointer (but then you have to remember to delete it, in the calling code, which is weird)
Yes, you have to remember to delete it as you do not want to consider automatic cleanup for this question.
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)
Returning reference is useful when you are returning this object(*this) from member functions. Otherwise, like you mentioned its not possible to use.
Overall: it depends upon your need as described above regarding which one to choose when.
Upvotes: 0
Reputation: 224039
A few rules of thumb regarding returning objects from functions:
Return per copy, except when
const
reference; you can return this per const
referenceconst
referenceUpvotes: 3
Reputation: 262919
Assuming "no library handling pointers and freeing memory automatically" means no return-by-pointer, no boost::shared_ptr
and no std::unique_ptr
(std::auto_ptr
is evil anyway), you have two choices:
Return by value:
Foo bar(quux)
{
Foo foo;
foo.frobnicate(quux);
return foo;
}
Foo foo = bar("fred");
Pass by reference:
void bar(Foo& foo, quux)
{
foo.frobnicate(quux);
}
Foo foo;
bar(foo, "fred");
Upvotes: 2
Reputation: 11130
Personally I prefer the second option because it is clear that the user needs to allocate and delete memory.
Upvotes: 0
Reputation: 36852
Depends on the "semantics" of the object. Values should be returned by copy while entities should (or must, since they are ideally not copyable) be returned by pointer or reference.
References should be used when possible. But if you must return a pointer, using a smart pointer class such as std::auto_ptr or boost::shared_ptr is a good idea, because then the calling code don't have to wonder about freeing it when it is done with it.
Upvotes: 1
Reputation: 263088
Return by value unless you need subtype polymorphism. In the latter case, I would return an auto_ptr<T>
(C++03) or a unique_ptr<T>
(C++0x).
Upvotes: 0
Reputation: 54128
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.
Upvotes: 8
Reputation: 132984
What about std::auto_ptr
from <memory>
? Or if C++0x is concerned std::unique_ptr
?
Upvotes: 3