Re: by-const-ref vs. by-value
red floyd wrote:
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.
Not necessarily. Only if the object referred to through the reference
is actually defined as a const object will the behaviour be undefined.
For example,
void mutate(const int& i) { const_cast<int&>(i) = 0; }
int i = 1;
mutate(i);
the behaviour of this code snippet is well-defined.
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&.
I'm not very sure what you mean here, but even if T::operator+=()
doesn't modify the right-hand side, val could be aliased with one
of the objects referred to by *beg and changed by the assignment.
This is perfectly valid and doesn't cause any error with regard to
the constness of the reference, as long as *beg, through which val
was changed, is a non-const reference.
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]