Re: What's the point of passing parameter by value (vs. const ref)
"Andrew Koenig" <ark@acm.org> a ?crit dans le message de
news:G94bk.91687$102.27047@bgtnsc05-news.ops.worldnet.att.net...
"Martin T." <0xCDCDCDCD@gmx.at> wrote in message
news:g4ferd$sji$1@registered.motzarella.org...
When writing new C++ code, what is the point of passing any (input)
parameter by value when passing by const reference will just work as
well?
One possibility is that you might be mistaken about whether it works just
as
well.
Here's an example:
// Divide all the elements of a vector<double> by a constant
void vec_divide(vector<double>& v, const double& x)
{
for (vector<double>::iterator it = v.begin(); it != v.end();
++it)
*it /= x;
}
Now consider what happens when you call
vector<double> v;
v.push_back(1.23);
v.push_back(4.56);
vec_divide(v, v[0]);
If you don't see the problem, try running it.
good example !
another one:
#include <iostream>
void f(int * p, const int & x)
{
++(*p);
}
int main(int argc, char *argv[]) {
int x=1;
int * p=&x;
f(p,x);
std::cout<<x;
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]