Boost logo

Boost :

Subject: Re: [boost] [move] moving temporaries of copyable types
From: klaus triendl (klaus_at_[hidden])
Date: 2009-06-21 16:40:21


Ion Gaztañaga schrieb:
> klaus triendl wrote:
> > So, my question is whether this is well-known and this feature was
>> deliberately excluded from Boost.Move or nobody has discovered it yet.
>> It would be great to have support for copy- and (implicit)
>> move-semantics.
>
> I didn't know about this feature. Could you elaborate a bit? And it
> would be even better if you could modify the library to support this
> feature ;-)

Well, it's actually very simple: add not only a user-defined conversion
to rv<T>& but to const rv<T>& as well and have a ctor/assignment
operator handling the const rv<T>&.
Compilers will choose then a conversion operator based on the
const-qualification of an object. This technique is working on msvc9.

I let a short code example speak:

<code>
template<typename T>
class rv: public T
{};

class copyable_and_movable
{
   typedef copyable_and_movable type;

public:
   // non-const lvalues bind here
   copyable_and_movable(copyable_and_movable& other)
   {}
   // const lvalues and const rvalues bind here
   copyable_and_movable(const rv<type>& other)
   {}
   // non-const rvalues bind here - temporaries!
   copyable_and_movable(rv<type>& other)
   {}

   // ... assignment operators ditto

   operator rv<type>&()
   {
     return static_cast<rv<type>& >(*this);
   }
   operator const rv<type>&() const
   {
     return static_cast<const rv<type>& >(*this);
   }
};
</code>

I'm not quite sure yet how Boost.Move could support this - the caveat
lies in having essentially two copy constructors.
A possible idea is:

Extend the BOOST_ENABLE_MOVE_EMULATION macro to include the const
conversion operator.

Provide a macro for the const-copy ctor:
#if !defined(BOOST_HAS_RVALUE_REFS)
# define BOOST_CONST_RV_REF(TYPE) const boost::rv< TYPE >&
#else
# define BOOST_CONST_RV_REF(TYPE) const TYPE&
#endif

When writing copyable_and_movable guard the non-const-copy ctor with the
BOOST_HAS_RVALUE_REFS macro.

In code:
<code>
class copyable_and_movable
{
   typedef copyable_and_movable type;

public:
#if !defined(BOOST_HAS_RVALUE_REFS)
   // non-const lvalues bind here
   copyable_and_movable(copyable_and_movable& other)
   {}
#endif
   // const lvalues and const rvalues bind here
   copyable_and_movable(BOOST_CONST_RV_REF(type) other)
   {}
   // non-const rvalues bind here - temporaries!
   copyable_and_movable(BOOST_RV_REF(type) other)
   {}

   // ... assignment operators ditto

   BOOST_ENABLE_MOVE_EMULATION(type)
};
</code>

Attached you find a sample project just showing my tests without using
Boost.Move.

Best,
Klaus




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