Boost logo

Boost :

From: Terje Slettebø (tslettebo_at_[hidden])
Date: 2002-10-16 02:20:17

>From: "Pavel Vozenilek" <pavel_vozenilek_at_[hidden]>

> >From: "Terje Slettebø" <tslettebo_at_[hidden]>
> >>From: "Pavel Vozenilek" <pavel_vozenilek_at_[hidden]>
> >>
> >> operator+() can be implemented like described in
> >> (Stewe Dewhurst's
> Gotcha#36).
> >> ...
> > Yeah, but that would be cheating. :) ....
> > ... In other words, getting the wrong result fast is never a bargain. :)
> >
> Cheating is way too strong word.

I meant in this case, for the example I had. Like I said, it wasn't a
complete example, and it's unlikely that the "array" member wouldn't be
copied at all, which is what your code did, it didn't copy it. Perhaps you
misunderstood me?

> It is technique that may or may not speedup
> the code, e.g. :
> - only one constructor is called (thus dynamically allocated members (if
> any)
> need to be allocated only once and are not reallocated)
> - depending on the class, some code otherwise invoked during copy can be
> avoided
> - it is ideal situation for RVO

Yes. Like I said, the point of a computational constructor is valid. What I
referred to as "cheating" was that your implementation had taken advantage
of that my example was incomplete - the operator+=() didn't do anything with
"array", except copying - hence you simply removed the copying completely.

> > Test(const Test& lhs, const Test& rhs) : num(lhs.num + rhs.num)
> > {
> > std::memcpy(array,lhs.array,1024*sizeof(int));
> > }
> >
> > And then we're back to having a copy in the code, after all.
> >
> If this trick is not used, memcpy() will likely be called twice: during
> constructor
> and then during operator+=().

operator+=() in my version called the copy constructor, to make the target
object, which would then call memcpy, yes. But it should only call it once,
provided the NRVO is used. It's supposed to call memcpy when using the
operator+=(), in this case, in order to copy "array".

If it's still unclear, I can provide a more complete class, using the NRVO,
and then you can try to make it more efficient, using a computational
constructor. However, for a compiler that supports NRVO, I don't think
you'll get it more efficient. What you may get is that it's more efficient
for compilers supporting RVO, but not NRVO, as mentioned in the previous

> I once modified Alexandresu'c flex_string<> and time needed for
> dropped down to 50-75%, depending on string length (with VC++ 6.0).

Interesting. Have you sent it to him, or could you send it to me?

I guess you've also seen his postings about ZUTO.

> IMHO this technique makes sense for very performance sensitive classes
> because
> standard copy constructor and operator+=() need to be coded separately,
> resulting in code duplication.

I guess you could factor out common code in a function.



Boost list run by bdawes at, gregod at, cpdaniel at, john at