When you define a function like: void func(int x);
then you're passing arguments by value.
When you define a function like: void func(int &x);
your passing arguments by reference (modifiable).
But, when you define functions like: void func(constint &x);
x is a reference to const (not modifiable but no extra variable).
So, when creating functions should I always make parameters a reference to const if I just need to use the value? So less memory is used? Obviously, I would use reference for modifying values.
Also, what is the difference between these?
1 2
template <typename T>
T func(T const& x);
1 2
template <typename T>
T func(const T &x);
Which one is better for creating functions that use the value but not modify it?
A reference when used as a parameter to a function is actually a pointer. Thus you add a level of indirection.
A const reference supports an implicit conversion. That means if the provided type does not match the referenced type a temporary object will be created that uses the appropriated constructor for the conversion.
It is actually thinkable that the compiler optimizes away the indirection if possible. So in doubt const reference is a good choice (nobody can recommend to use something always).
So less memory is used?
This cannot be answered since it is compiler dependant.
Obviously, I would use reference for modifying values.
I wouldn't recommend that because that might lead to surprises where you don't expect modification.
For simple types like int, double, bool, etc. there is no need to pass by const reference. The size of a pointer is often at least as big as these types so you wouldn't be saving any memory. The extra indirection to read the value through a pointer could also slow down the program a tiny bit. It's probably not enough to have any noticeable effects, and the compiler might be able to optimize away any overhead of passing by reference, but if there is a syntactically simpler way (i.e. passing by value) that is almost guaranteed to be equally and possibly faster than a more complicated way (i.e. passing by reference) I don't see why I would not go for the simpler way.
My rule of thumb is to pass simple built-in types like char, int, double, bool and also enumerations by value and class types (structs included) by const reference.
will it be the more efficient than without const reference since the compiler will optimize?
And, when using references you cannot provide default values in parameters like: int add(int x = 0, int y = 0);
so then using const reference is a disadvantage? Any work arounds?
Peter87 wrote:
My rule of thumb is to pass simple built-in types like char, int, double, bool and also enumerations by value and class types (structs included) by const reference.
Your rule of thumb and explanation doesn't seem to match.