Boost logo

Boost :

From: Daniel Frey (d.frey_at_[hidden])
Date: 2002-10-12 09:38:03


On Sat, 12 Oct 2002 14:26:04 +0200, Terje Slettebø wrote:

> - The posting with the patch
> (http://lists.boost.org/MailArchives/boost/msg31458.php) says "See also
> Scott Meyers "More Efficient C++", Item 4.7.". There's no Item 4.7, and
> Item 4 doesn't seem to apply, so I wonder what is referred to, here?

Maybe it's another item number in the english book, I only had the german
translation at hand.

> - The same posting uses "friend const T operator+()" in the posting, but
> "friend T operator+()" in the patch. Which one will be used, and why?

> "Effective C++", Item 21, "Use const whenever possible" argues for
> returning const UDTs, to avoid operating on temporaries, such as "(a *
> b)=c". This would also be illegal for built-in types. Why then not
> return "const T" in operators.hpp? The const is ignored for built-in
> types (as they have no "this"), but prevents the operation on
> temporaries, such as the above.

I think it's in the patch in the files-section, isn't it? 'const T' is
IMHO the type that should be returned. If the patch returns 'T', it's an
error. Please note that the only current version is the patch, not any
code I attached to a posting.

> - "More Effective C++", Item 20, "Facilitate the return value
> optimization" argues for using the constructor in the return statement,
> rather than creating a named temp. The argument is that although NRVO is
> also now possible, RVO (unnamed temporary) has been around longer, and
> may therefore be more widely implemented. Thus, compilers implementing
> NRVO almost certainly implements RVO, but not necessarily the other way
> around. Given this, why isn't the following used in operators.hpp:
>
> friend T operator+( const T& lhs, const T& rhs ) {
> return T(lhs)+=rhs;
> }

Please read Scott's errata. You actually return a T& that was supplied by
operator+= and therefore, the compiler is not allowed to apply the RVO.
It would be different, if you have a function like this:

friend T operator+( const T& lhs, const T& rhs ) {
   return T(lhs);
}

But obviously this function doesn't do what one expects from operator+ ;)

Regards, Daniel


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