Transmit parameter by value or by reference in C++? [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pass by reference more expensive than pass by value
I want to know which is better, sending parameters by value or by reference in C++. I heard that there are cases where sending by value is faster than sending by reference. Which are these cases?
Thanks

As a general rule, you should pass POD types by value and complex types by const reference.
That said, a good place where you pass complex types by value is where you would need a copy of the object inside the function anyway. In that case, you have two choices:
pass the argument as a const reference and create a local copy inside the function
pass the argument by value (the compiler creates the local copy).
The second option is generally more efficient. For an example, see the copy&swap idiom.

The obvious case is when the parameter is equal to or smaller than a pointer in size and trivial to copy -- then you would pass by value. However, this is a age-old discussion and quite a long answer is required to answer it correctly for a given architecture. There are also many corner cases (e.g. RVO).
There's more to the question than speed -- semantics should be your first priority.
See also: Is it better in C++ to pass by value or pass by constant reference?

Related

What are the advantages of passing a reference to an object? [duplicate]

This question already has answers here:
Is it better in C++ to pass by value or pass by reference-to-const?
(11 answers)
Closed 7 years ago.
I studied that objects can be passed by referece (I mean that the parameters of the function are references). But why one prefers them over simply passing objects. My motive is to just use that object and in no sense modify it, so I do not mean the trivial advantages. So, what are the advantages of passing a reference to an object?
Here are some advantages of passing by reference:
No new copy of variable is made, so overhead of copying is saved. This
Makes program execute faster specially when passing object of large structs or classes.
Array or Object can be pass
Sometimes function need to change the original value(eg. Sorting an array, swapping) and sometimes changing value inside function is useful.
Can return multiple values from a function.

Is it faster to return a value or to use pointer parameters [duplicate]

This question already has answers here:
How to "return an object" in C++?
(8 answers)
Closed 9 years ago.
I wanted to know if it is faster to normally return a value from a function or to use a pointer as a parameter and pass the value to that pointer.
In different common ABIs, return-by-value for large (not fitting in registers) objects is implemented through a pointer anyways. The caller reserves the space, and passes a pointer to the callee, that uses that pointer to create the object in place.
With modern Compilers and C++11 returning by value is fastest in many cases: Want Speed? Pass by Value. (Archive)
I will assume we're talking about C++11 here, since it's been 2.x years already.
Start by returning your object by value: move semantics, (N)RVO can kick in and generate really fast code that is really easy to read. However, if you profile your code and find that this particular function is a bottleneck, consider using a reference as an "out-parameter." This may in fact be faster than using a pointer, as the compiler has more flexibility with how to represent a reference. The ISO standard for C++ does not dictate that references require storage, so the compiler is free to make the reference a literal alias of the other memory location, using effectively zero bytes of overhead.
All in all though, write the cleanest code first, and then measure it. People underestimate just how much optimization the compiler can do for you if you just return your (movable) objects by value.
Pointer is 4 or 8 bytes long depending on the architecture.
If your value is less that that in size, it might be faster to pass values.
If you have large objects and copy constructors, then more memory will be copied and passing that kind of parameters would be more expensive.
But... compiler optimizations, memory alignment, and other sorcery, might need you to directly investigate this in YOUR case.
In return by value case, assume the caller has an object to pass the compiler will crate a copy of that argument which is more or less equivalent to the cost of pass by reference. So from performance point of view either solutions seems equivalent.

What is the point of const being used with pass by reference? C++ [duplicate]

This question already has answers here:
Why pass by const reference instead of by value?
(8 answers)
Closed 9 years ago.
I was reading a book on C++ and there was an example where they passed by reference a constant to a function.
int square(const int& n)
...
I can't see the point of this? Why not just pass it normally by value if you are not going to be making any changes to the variable. Isn't the whole point of passing by reference so you can change the value of a variable.
It probably makes no real difference for an int. But for a larger data type then passing const reference is a performance optimisation. So many coders just use const reference instead of by value out of habit.
For complex types, passing by value is much more expensive than passing by reference because a copy of the value has to be made to pass to the function. Consider passing a large vector to a function that computes the median value. Do you really want to allocate a new vector, copy all the values in, perform the average over the new vector, and then free the memory you allocated? Passing by reference saves the allocate/copy/free cycle.
For int, it doesn't matter. In fact, on most platforms passing by value will be cheaper.
If you pass it by reference, you only pass the pointer, which is a "smaller" thing to pass. Also, the object is not copied in your function, so you use less memory in total.

Returning vs. using a reference parameter [duplicate]

This question already has answers here:
Which is more efficient: Return a value vs. Pass by reference?
(7 answers)
Closed 1 year ago.
This is really bugging me, coming from a C# background.
Sometimes, I see functions written like this:
int computeResult();
This is what I'm used to. But then I see them written like this:
void computeResult(int &result);
I find this strange. What benefits does the second method have over the first, if any? There must be something, since I see it all the time.
There are two common reasons for such non-const reference parameters:
You may need multiple "out" parameters in a function, and using reference parameter(s) allows for this.
Your object may be expensive to copy, and so you pass in a reference that will be mutated rather than returning an object that may get copied as part of the return process. Expensive-to-copy objects may include standard containers (like vector) and objects that manage heap memory where an allocation-copy-deallocate sequence would occur. Note that compilers are getting really good at optimizing away these copies when possible and so this reason has less import than it used to.
EDIT: I should clarify that even in C++ the specific example you've provided with a single builtin type reference parameter is pretty atypical. In such cases a return value is almost always preferred.

How to pass a std::shared_ptr<Resource> to a function? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Should I pass a shared_ptr by reference?
Passing smart pointers as arguments
Should I pass it by value or by constant reference? I have read numerous rules of thumb on whether to pass a copy constructible object by value or by constant reference. Such as:
pass objects by constant reference and built in types by value (except function objects)
pass by value unless size of the object (including dynamic memory) is less than 2 * size of a double.
Could you explain how do these rules apply to std::shared_ptr<Resource>? I understand that the object is probably very small, likely a pointer and a reference counter, but it is still an object. What is the best practice here?
Perhaps the most important concern (with regards to performance) is that creating a copy of a std::shared_ptr<...> (such as happens when you pass by value) requires an interlocked increment of a reference count. Or maybe some other form of synchronization like a critical section, depending on implementation. Such a cost could be significant in a multithreaded program.
Passing by reference is almost certain to be a better choice. It's main drawback (or is this only with boost::shared_ptr<...>?) is that shared_ptr<...> offers only the standard thread safety guarantee: access to a single shared_ptr<...> must be guarded (e.g. by a mutex) unless all accesses are only to const methods. In a multithreaded situation, passing around const references to shared_ptr<...>s may make it more difficult to ensure proper synchronization.
In a single threaded program, it probably doesn't make much of a difference.