Re: 'academic' problem ( speed/memory efficiency vs. human readability and
SeeWebsiteForEmail@erdani.org (Andrei Alexandrescu (See Website For
Email)) wrote (abridged):
Earl Purple wrote:
Optimal (won't create a temporary then copy it) at the cost of
showing the user the implementation.
I'm not sure I understand. Aren't value parameters all but
indistinguishable from const reference parameters? What does the caller
care?
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.
But then taking a parameter by value that you could take by const
reference could be considered "harmless" and the only reason
you'd take by const reference is to optimise.
I think one can safely replace "could be considered" with "is".
Indeed. However, if we apply this optimisation uniformly whenever the
object is expensive to copy, then it does not depend on the implementation
of the particular function and so does not leak that implementation.
So which one would you call premature optimisation?
None. There is no extra effort involved - actually, often it's less
effort.
As I noted above, what is be optimal for the base class might not be
optimal in the derived class. Using pass-by-copy in this way is making a
commitment to copying that may turn out to be a pessimation. So I do see
it as a premature optimisation: more fully, a premature commitment for
purposes of optimisation.
-- Dave Harris, Nottingham, UK.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]