is there a similar construct for when we want to avoid copying when returning objects/containers from functions? |
If the situation permits, you could pass the object by reference and have that function modify it. The function would now return void. Besides that, no, if you return an object from a function, there would be a copy on the caller's side. Fortunately, most (all?) popular compilers support return value optimization
*, so the temporary object placed in the return value will not be created if you have optimizations turned on, situation permitting of course.
I am a firm believer of if there's no
observed performance problem, then there's no performance problem. That is, if the overhead of copying objects on function returns isn't causing any noticeable slowdown, then there really isn't anything to worry about yet.
Or is the only solution to is to pass pointers around and use new inside the functions (this seems ugly)? |
Your intuition is right:
don't pass pointers around just to avoid copying overhead. It just tarnishes the legibility of the program.
*http://en.wikipedia.org/wiki/Return_value_optimization