Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits to passing integral types by const ref

Tags:

c++

reference

The question: Is there benefit to passing an integral type by const reference as opposed to simply by value.

ie.

void foo(const int& n); // case #1

vs

void foo(int n); // case #2

The answer is clear for user defined types, case #1 avoids needless copying while ensuring the constness of the object. However in the above case, the reference and the integer (at least on my system) are the same size, so I can't imagine there being a whole lot of difference in terms of how long it takes for the function call (due to copying). However, my question is really related to the compiler inlining the function:

For very small inline functions, will the compiler have to make a copy of the integer in case #2? By letting the compiler know we won't change the reference can it inline the function call without needless copying of the integer?

Any advice is welcome.

like image 262
DeusAduro Avatar asked Nov 13 '09 06:11

DeusAduro


People also ask

What is one benefit of declaring the parameter as a const reference?

What is one benefit of declaring the parameter as a const reference instead of declaring it as a regular object? Actually, objects cannot be passed as regular variables, because they require a constructor call. Therefore, a const reference is the only way to pass class instances to functions.

Why is it better to pass by reference?

Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument.

What is the point of a const reference?

For instance, const references allow you to specify that the data referred to won't be changed; this means that you can use const references as a simple and immediate way of improving performance for any function that currently takes objects by value without having to worry that your function might modify the data.

When should you pass by reference C++?

CPP. 2) For passing large sized arguments: If an argument is large, passing by reference (or pointer) is more efficient because only an address is really passed, not the entire object.

Does const reference extend lifetime?

In the by-reference case, we get a const Base& reference that refers to a Derived object. The entire temporary object, of type Derived , is lifetime-extended.


1 Answers

I actually find it irritating when somebody uses const references like this for the basic datatypes. I can't see any benefit of doing this, although it may be argued that for datatypes bigger than sizeof(pointer) it may be more efficient. Although, I really don't care about such minute 'optimizations'.

like image 60
Naveen Avatar answered Oct 02 '22 09:10

Naveen