Boost logo

Boost :

From: Dave Harris (brangdon_at_[hidden])
Date: 2002-11-19 16:31:35

In-Reply-To: <20021119153535.GB589_at_[hidden]>
On Tue, 19 Nov 2002 16:35:36 +0100 Wesley W. Terpstra
(terpstra_at_[hidden]) wrote:
> [On unnecessary copies]
> I think you may be interested to run this program:

It's a demonstration of the Return Value Optimisation, which I was already
aware of. The RVO is explicitly permitted, but not required, by the
standard. Some compilers don't provide it and it can't be relied upon.

> > void MyClass::load( basic_iarchive &ar ) {
> > MyClass( ar ).swap( *this );
> > }
> *This* might copy three times. (at least two)
> So, no better, and probably worse than above.

Not if swap() is written to avoid copying. If the members were vectors,
for example, this can be written to avoid copying the data in the vectors
at all. For example:

    class MyClass {
        vector<int> member1;
        vector<int> member2;
        MyClass() {
        MyClass( const MyClass &rhs ) :
               member1( rhs.member1 ),
               member2( rhs.member2 ) {
        MyClass( basic_iarchive &ar ) {
            ar >> member1 >> member2;
        MyClass &operator=( MyClass &rhs ) {
            MyClass( rhs ).swap( *this );
        void MyClass::load( basic_iarchive &ar ) {
            MyClass( ar ).swap( *this );
        void swap( MyClass &rhs ) {
            member1.swap( rhs.member1 );
            member2.swap( rhs.member2 );

Now neither of:
    MyClass example1( ar );
    MyClass example2;
    ar >> example2;

will copy the data in the vectors. To me this looks natural and elegant,
with the symmetry between the assignment operator and load function being
especially pleasing.

-- Dave Harris

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