Boost logo

Boost :

From: Andrei Alexandrescu (andrewalex_at_[hidden])
Date: 2002-10-13 13:44:54


"Mattias Flodin" <flodin_at_[hidden]> wrote in message
news:20021012213714.GA4386_at_krona.cs.umu.se...
On Sat, Oct 12, 2002 at 09:56:32AM -0700, Andrei Alexandrescu wrote:
> I recently reached the conclusion that taking a parameter by const
reference
> just to make a copy of it inside the function is a "lie". The signature
> says: "I don't need a value! A reference to a const is all I need!" and
the
> code says: "The first line of this function makes a copy!" There will be a
> section in my upcoming article entitled "The Lying const". Taking const& T
> as arguments in /any/ function when you actually *do* need a copy chokes
the
> compiler (and Zuto) and practically forbids them to make important
> optimizations.

>Why would I want to communicate information about what my implementation
does in the function interface? I don't see why putting const there
would be a lie; more like information hiding, which is usually
considered a good thing.<

The interface of the function doesn't change in the least whether you take a
value or a reference to const. As far as your clients are concerned, the
deal is the same.

Couldn't find a specific other post to stick this to, so here I'd like to
thank all, especially Terje, who participated to the RVO and NRVO
measurements and discussion.

I need to mollify my arguments against the lying const. But only a bit! The
operator+ example shows that many compilers prefer const T& as the first
argument in certain cases. However, in the case of assignment:

T& operator=(const T& src)
{
    T copy(src);
    copy.swap(*this);
    return *this;
}

versus:

T& operator=(T src)
{
    src.swap(*this);
    return *this;
}

I'd be quite surprised of the compiler could go past the const in the
argument.

Also, if a temporary is passed as the first argument to operator+, that also
might engender an unnecessary temporary. So "lying const" is too strong,
maybe I should go for evidentiating the opposite case, "The Friendly
Pass-By-Value" :o).

Anway, with ZUTO, the implementation of operator+ that is guaranteed to not
copy temporaries unnecessarily is the one that takes lhs by value. (Same
about operator=.) That result is regardless of whatever flavor of RVO the
compiler implements, if any. Of course, a compiler better at RVO would help
Zuto better by eliminating some of the call pairs to moving
constructors+destructors.

Andrei

P.S. The interest in ZUTO is staggering. The number of volunteering
reviewers has hit 70. If I made any mistake, I'm toast!!! :o)

--
All new!  THE C++ Seminar: Oct. 28-30 in Vancouver, WA.
http://www.thecppseminar.com/

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