Reputation: 805
I have an issue with the use of aliases in function arguments. Here is my problem.
Let's consider this function definition
void thisIsSparta(int& number){
...
}
at call time, it works perfectly well with the following code :
int king = 1;
thisIsSparta(king);
but I have a mismatch error when I try this :
thisIsSparta(1);
I can easily guess that the error occurs because there is simply no variable to alias, hence the error. However, I don't want the programmer to worry about using only one of the two approaches, this second function call should work as fine !
The only solution I see is to create another function with no alias argument, in addition to the first one :
void thisIsSparta(int number){
}
But this would result in an awful code duplication, and I'm not a huge fan of this.
Furthermore, the program could decide to use this second definition instead of the former when I use a variable. I then loose the interest of the alias, whose purpose is to avoid variable copy.
Does anyone have a solution to my problem ? Indeed, this is a simplified example, in practice I have a generic type in argument for this function, and it could be arbitrarily big. This is why I'd like to use an alias to avoid copy.
Upvotes: 1
Views: 4636
Reputation: 76245
The problem with passing the argument by reference is that the function can modify it:
void thisIsSparta(int& number) {
++number;
}
Now, what would thisIsSparta(1)
do? (No, this isn't ancient FORTRAN, where modifying constants was possible...)
If you want to pass non-modifiable variables, the function has to promise not to modify its argument:
void thisIsSparta(const int& number) {
// whatever
}
and, as others have pointed out, for builtin types, passing by value is always preferable to passing by const reference:
void thisIsSparta(int number) {
// whatever
}
Upvotes: 1
Reputation: 146910
Copying a primitive like int
is completely negligible. It's probably more expensive to pass a reference, for a few reasons.
Secondly, you can overload with
const int&
int&
This will select the second for all int
objects, and the first for temporaries and const int
objects.
Upvotes: 2
Reputation: 258588
For basic types, just pass by value. It's faster than passing a reference, so ditch the passing by reference and just have
void thisIsSparta(int number)
For large types, you can only bind temporaries to const
references, so you can declare the method as
void thisIsSortOfSparta(const MyClass& obj)
If you're modifying the value inside the function, then passing a temporary as argument doesn't make sense, so the compiler is right to complain, but in case you don't, use the above two options.
Upvotes: 4