Returning a large object from a function

Started by
5 comments, last by DevFred 14 years, 5 months ago
If you want to return a large (or expensive to copy) object from a function, you can either return it directly:
std::vector<std::string> Generate();
Or return it through an out parameter:
void Generate(std::vector<std::string>& out);
The first relies on the compiler to perform RVO to elide the extra copies, which should make it just as performant as the second version. But RVO isn't exactly difficult to inadvertently defeat, causing a lot of copying overhead. So in general, which do you prefer any why?
NextWar: The Quest for Earth available now for Windows Phone 7.
Advertisement
I can't believe we still have to worry about this in 2009. :(
I pretty much always use the out parameter method for non-primitive types... C++ doesn't have multiple return values anyway, so the out parameters wouldn't be completely avoidable regardless.
Through an out parameter. Not because of any
technical reasons but rather that the return
value can be used for return/error codes.

I like to be as consistent as possible when
I have choice so I do it that way as often
as possible even when return codes aren't
very meaningful for that particular function.
I usually return large objects from factory functions by auto_ptr. It's actually quite rare that a profiler tells me that this is a mistake.
Quote:Original post by SiCrane
I usually return large objects from factory functions by auto_ptr. It's actually quite rare that a profiler tells me that this is a mistake.


This.

I use this idiom quite heavily and it almost always ends up being acceptable when it comes time to start profiling code. It also reinforces the idea that dynamically allocated objects should be handled by smart pointers rather than raw pointers/references as much as possible. Last but not least, it avoids having to deal with deep-copy issues if you use by-value returns; in my experience the real killer isn't objects getting copy constructed per se - it's usually the classes with really nasty deep-copy semantics that end up being the problem.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Quote:Original post by Sc4Freak
The first relies on the compiler to perform RVO to elide the extra copies

And in the rare cases where RVO doesn't kick in, you still have move semantics as a safety net. All of the standard library containers are going to have move constructors in C++0x.

Quote:Original post by Beyond_Repair
C++ doesn't have multiple return values anyway

You can return a tuple if you need more than one return value.

Quote:Original post by Pzc
Through an out parameter. Not because of any technical reasons but rather that the return value can be used for return/error codes.

C++ has a dedicated language mechanism for signaling errors.

This topic is closed to new replies.

Advertisement