Boost logo

Boost :

From: Søren Lassen (s.lassen_at_[hidden])
Date: 2005-04-25 14:31:11


On Mon, 25 Apr 2005 13:01:58 -0400, Philippe Mori
<philippe_mori_at_[hidden]> wrote:

> You might look into the book "C++ Coding Standard" by Herb
> Sutter and Andrei Alexandrescu at items 27 and 55 in particular.
>
> If operators returns const objects the many functions should probably
> also returns const objects.
>
> As mentionned in the book, returning const objects disable some
> usefull construct on temporary objects (like calling a non-const
> member function) and might break some existing client code.
>
> So for consistency, I think that boost operators should returns
> non-const objects as most librairies do (including probably the
> STL for complex numbers).

Well, according to my guru, that is not how things are supposed to work.
See Scott Meyers' "Effective C++" 2nd Edition, page 91. His main point is
that user-defined types should behave like the built-in types - meaning
that a construct like
        (a * b) = c;
should be illegal, whether a,b, and c are integers, floats or
user-defined. So, for consistency, I think that boost operators should
return const objects.

More generally, he writes (same page): "Having a function return a
constant value often makes it possible to reduce the incidence of client
errors without giving up safety or efficiency". So yes, I think you are
right, many (most) functions should also return const objects.

I suppose, though, that there may be situations where it may be of
interest to call a non-const member function on a temporary object,
although this sounds a bit like sloppy programming to me. In terms of
operators.hpp, however, this is rarely the case, as the binary operators
are declared inline, meaning that the return values in most cases are
constructed right in the target variables. Therefore I think that e.g.
        x=(a+b).somenonconstfunction();
will rarely be faster than
        UserType y=a+b;
        x=y.somenonconstfunction();

You are right about the complex numbers in the STL. And this, of course,
makes programming constructs like
        complex<float> x=((a*b)+=c);
possible. But because the complex operators * and + are declared inline,
there is no reason to think that this is faster than
        complex<float> x=(a*b)+c;
only harder to read, and non-compatible with built-in types. And it is
never faster than
        complex<float> x=(a*b);
        x+=c;
I do not see any realistic uses of the non-const return values from the
binary operators in complex.h. Can you give me an example?

And more importantly, are there boost libraries or client libraries that
depend on the non-const-ness of the binary operator results in
operators.hpp?

---
Søren

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk