Assigning to an object
Is there any reasonable ex开发者_开发百科planation of following techinque:
//value HAS TO BE CHANGED those are requirements
int f(int value)
{
int tmp = value;//In order to not change "value" inside fnc - again requirements
//do something with tmp
return tmp;
}
int a = 0;
a = f(a);//here I assign to a anyway
instead of this:
void f(int& value)
{
//do something with value
}
or this:
int f(int& value)
{
//do something with value
return value;
}
and would you agree that first code snippet is (in general) an example of bad programming practice?
I don't see a reason for the tmp = value
bit since in the first version, the parameter isn't a reference, but I think it's often a good practice to take the parameter by value, and then return an updated copy, instead of taking and modifying references. Fewer side effects makes the code easier to reason about.
So I'd say the nicest version is this:
int f(int value)
{
//do something with value
return value;
}
int a = f(a);
I'm not sure why you insisted on making the parameter a reference in your third example.
If you really do not want to change value
, make it const
. But honestly, I see no reason to do so.
If you needed the original value of value
for reference. For example, if you wanted to do some operations on it and then compare to see if it was the same afterwards. And return the value.
Seems a little obscure, but it would make sense.
One reasonable explanation I can think of for the first version is that you can use the function even if you don't want to modify the parameter, but only return the result. I wouldn't agree that writing a function like that is bad programming practice.
It depends on what is desired by programmer precisely. For this use a = f(a)
, I don't see a difference since the result will obviously be same. But considering in general, a use such as a = f(a) + f(a)
would give a different result. So I can't say it's totally a bad programming practice.
It all depends on how you want to use the function. For example you can evaluate the first version of the function like so:
avariable = f(avalue)
Only avariable
will change.
You can use the second version of the function like so:
f(&avalue)
Only avalue
will change.
You can use the last version of the function like so:
avariable = f(&avalue)
Both avariable
and a avalue
will change.
They all have their uses. It depends on what you as the programmer need from them. Just ask yourself: Which variable(s) do you need returned modified by the function?
You could need the original value for some use, it depends on what you have to do. For instance, a temporary variable could be used to store one of the two parameters during "swap" (although there's a built-in swap function in the STD):
void swap(int& first, int& second) {
int tmp = second;
second = first;
first = tmp;
}
精彩评论