Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency of output parameter vs return value on the stack for stl data structures

lets say I have the functions

std::Vector<Point> calculate() {
   std::Vector<Point> points; //do stuff with points
   return points;
}

and

void calculate(std::Vector<Point>& points) {
   //do stuff with points
}

So my question is specific to objects initialized on the stack, and are stl objects. Is there any difference in performance, and what is the popular method of doing it

regards

like image 622
Moataz Elmasry Avatar asked Aug 21 '12 14:08

Moataz Elmasry


People also ask

What is difference between output parameter and return value?

When you want to return one or more items with a data type then it is better to use an output parameter. Generally, use an output parameter for anything that needs to be returned. When you want to return only one item with only an integer data type then it is better to use a return value.

Which is generally more efficient a function that returns an object by reference or a function that returns an object by value?

Returning the object should be used in most cases because of an optimsation called copy elision. However, depending on how your function is intended to be used, it may be better to pass the object by reference.


1 Answers

My humble opinion: return values create more problems than solve... they look simpler, they are more concise in the calling segment, but rvalue references would be avoided...

The shortcoming is that expressiveness will be reduced, but that is a small cost, since resources like memory allocation will move upstream.

C++ must and can be significantly simplified in terms of syntax and resource management.

like image 51
Pedro M Areias Avatar answered Oct 04 '22 20:10

Pedro M Areias