Re: 'academic' problem ( speed/memory efficiency vs. human readability and
Dave Harris wrote:
I'm not Earl Purple, but when I've played around with this approach I
found it did leak implementation. If you switch between copy and
const-reference depending on whether the function body needs to make a
copy, you'll find that functions that conceptually should have the same
interface in fact do not. This shows up with virtual functions. A function
that makes a copy won't override one which doesn't make a copy.
In practice, that's not acceptable, so if the base class function uses
pass-by-copy, then all overrides must. This may lead to unnecessary copies
when calling the overriding function. Thus it is not always optimal.
If the base class function doesn't need to make a copy and therefore uses
pass-by-reference, overriding functions must too, even if they do need to
make a copy. This means that you cannot have a consistent style rule
saying "pass by copy only if you need a copy".
If the base class function implementation changes from making a copy to
not making a copy, would you update its signature? And find all the places
it is overridden too?
To me it all seems messy and inconsistent. When I am writing my
overloading function, I don't want to have to know whether the base
function uses this optimisation. I prefer function signatures not to
depend on function implementations. It just seems simpler.
Ideally it would be nice if the implementation of the function could
modify the parameter from const T& to T and the compiler would optimise
that to construct exactly one new object, so if the original reference
was bound to a temporary it would not copy it but if it were not bound
to a temporary then it would.
Now the compiler must know whether the const reference is bound to a
temporary or not - because of the lifetime of the variable. When it is
a temporary bound to a const reference its lifetime ends with the scope
of the const reference, whereas if it's a straightforward const
reference it does not.
So given the compiler definitely knows what to do, if we were allowed
to change it in the implementation file (after all they are logically
equivalent) then it would satisfy everybody, and would also get around
the virtual function situation where some implementations may want to
play with the copy and some may not.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]