In-Reply-To: <[EMAIL PROTECTED]>
On Tue, 19 Nov 2002 16:35:36 +0100 Wesley W. Terpstra 
([EMAIL PROTECTED]) 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;
    public:
        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

_______________________________________________
Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost

Reply via email to