Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2004-01-10 12:22:33


On Jan 9, 2004, at 9:27 PM, David Abrahams wrote:

> "Peter Dimov" <pdimov_at_[hidden]> writes:
>
>> Executive summary: the reference wins. It doesn't really matter. You
>> knew
>> that already.
>
> Yep, my tests show the same. That's a relief to me, actually. I
> wonder what Andrei was on about?

Andrei was making a point that Peter's test does not elucidate.

If you must modify the argument internally, then it is better to pass
the argument by value and modify the argument directly, rather than
pass by const reference, and make a copy of the argument which you can
then modify:

struct X
{
     X()
     {
     }

     X(int)
     {
     }

     X(X const &)
     {
         std::cout << "X(X const &)\n";
     }

     void modify() {}
};
...
struct A
{
     A(X x) {x.modify();}
};

struct B
{
     B(const X& x) {X(x).modify();}
};
...
     {
         std::cout << "A a(x);\n";
         A a(x);
     }

     {
         std::cout << "A a( (X()) )\n";
         A a( (X()) );
     }

     {
         std::cout << "A a(1)\n";
         A a(1);
     }

     {
         std::cout << "B b(x);\n";
         B b(x);
     }

     {
         std::cout << "B b( (X()) )\n";
         B b( (X()) );
     }

     {
         std::cout << "B b(1)\n";
         B b(1);
     }
...
A a(x);
X(X const &)
A a( (X()) )
A a(1)
B b(x);
X(X const &)
B b( (X()) )
X(X const &)
B b(1)
X(X const &)

Design A saves a copy over design B when client code passes a temporary.

-Howard


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