Re: Don't pass by reference to non-const?
"Thomas J. Gritzan" <phygon_antispam@gmx.de> >>
std::vector<double> v(...);
for (... lot's of iterations ... )
{
// calculate some values based on the current contents
// of v.
some_function(&v, ... the calculated values ...);
// ...
}
In this example you clearly use the vector as INOUT parameter, and have
a performance gain from that fact. Originally we were talking about
OUT
parameters...
No. The performance gain comes from the fact that he only allocates
memory once and uses this memory for all iterations.
Of course. And then what your "No" applies to? That preallocated memory
is IN param used in the called function. That is why it is not out, but
inout case.
When passing memory counts as IN param, then every OUT parameter is also
an IN parameter, because if you wouldn't pass (pointers to) memory in,
you would have no place to store the OUT parameters.
IMO that is a too simplistic and impractical view.
If the called function does like:
void foo( Vector & param)
{
Vector res;
/// ... fill res;
param.swap(res);
}
then it uses param as out only. Any state param could have will not leak
in. However,
{
param.resize(0);
param.reserve(100);
// do 100 push-backs
}
or
{
param.resize(100);
// assign to elements [0] - [99]
}
uses the state of param as it was passed in. And performance of the function
will be different in latter cases if you do just
Vector v();
or also do
v.reserve(100);
before calling foo(v);
Or like in a loop example just let it roll -- the first time allocation
happens then all the further calls keep the block.
Selling this as pure OUT parameter will not fly in my terminology.
The issue is not straightforward because the state of contained elements do
not differ in the alternatives. But capacity() is also part of the state.
With another collection, we could have similar state but entirely private,
and it still would count.