Boost logo

Boost :

From: Pavel Vozenilek (pavel_vozenilek_at_[hidden])
Date: 2002-10-14 22:47:24


"Terje Slettebø" <tslettebo_at_[hidden]> wrote in message
news:03b201c2722f$339fb850$60fb5dd5_at_pc...
> Sorry, this should be:

> inline Test operator+(const Test &t1,const Test &t2)
> {
> return Test(t1)+=t2;
> }

> The result is the same, though, as it inlines it, anyway.
>
operator+() can be implemented like described in
http://www.semantics.org/gotchas/gotcha36.pdf (Stewe Dewhurst Gotcha#36).
Modified test code is bellow: it uses private constructor and avoids any
copying in your case. The constructor can be tuned for this specific
operation.

(I tried your example on Intel C++ 7.0beta and result is code without any
rep movsb at all.)

operator+=() cannot be optiomized this way and should be used for testing.

/Pavel

-------------------------------------------------------------
class Test
{
private:
  // special private constructor to support operator+()
  friend Test operator+(const Test& lhs, const Test& rhs)
  Test(const Test& lhs, const Test& rhs) : num(lhs.num + rhs.num) {}

public:
  Test(int n) : num(n) {}

  Test &operator+=(const Test &other)
  {
    num+=other.num;

    return *this;
  }

  int num;
  int array[1024]; // Just so that copying shows up
};

Test operator+(const Test& lhs, const Test& rhs)
{
  return Test(lhs, rhs); // here's the trick
}


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