Boost logo

Boost :

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


On Sat, 12 Oct 2002 16:31:13 +0200, Howard Hinnant wrote:

> I think there are some existing valuable programming patterns for
> performing non-const operations on temporaries. Consider:
>
> #include <string>
> #include <iostream>
>
> int main()
> {
> std::string s1("abc");
> std::string s2("123");
> std::string s3 = (s1 + s2).replace(s1.size()-1, 2, "C4"); std::cout
> << s3;
> }
>
> abC423
>
> Now certainly there are other ways to achieve this same effect. Maybe
> those other ways or better, maybe they are not. But I assert that the
> above code is viable and reasonable. And it would not be possible if
> std::string + std::string returned a const std::string.

These patterns should IMHO be adapted to read like this:

std::string s3 = std::string(s1 + s2).replace(s1.size()-1, 2 "C4");

Although this will create a copy. The problem is, that you rely on
operator+ to return a temporary object. I have seen many cases where this
is true in the beginning of the development of a class, but when the
project grows, some things will be optimized. This may result in
temporary buffers of objects and functions returning references to these
objects. You won't notice the difference at first, but with your pattern,
you'd change an object in the buffer. This can lead to very nasty bugs
and I thus prefer to return const objects. It is more robust to changes
and easier to maintain. YMMV.

OTOH I can understand the fear to break existing code, so if the change
to return 'const T' seems to intrusive for the mayority of the boosters,
it can be taken out without breaking the NRVO.

> The above approach is generally not optimizable via RVO. The return
> statement sees a T&. Unless the compiler digs into op+=, it has no
> reason to believe that the T& refers to the temporary. Thus a copy of
> the object referred to by the T& must be made. If op+= returns by
> value, then that is another story of course (and that is the case that
> MEC++ #20 refers to).

Note that even if the compiler finds out that op+= return the temporary,
the standard itself forbids optimizations, as the observable result of
the program may be changed by removing the temporary. This is the basic
problem which can only be solved by the NRVO, the this optimization
explicitly allows observable changes!

Regards, Daniel


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