mardi 25 septembre 2018

std::bind doesn't use the move constructor

I have a class MyClass which has both a copy and move constructor. I try to send a MyClass object from one thread to another via a queue along with a functor. For this task, I use std::bind in the following manner:

someQueue.push( std::bind(
   [ this ]( MyClass & object ) { this->m_ObjectMember.addObject( object ); },
   std::move( localObject ) ) );

class MyClass
{
   public:
   MyClass( MyClass const& other );  <--- always called
   MyClass( MyClass && other );  <--- never called
   <...>
}

My problem now is that every time said std::bind is called the MyClass object (handed over via std::move( localObject ) is copied at least twice, I can see this from copy constructor call. I know that one call is from the construction of the MyClass object instance inside the functor returned by MyClass, however, since I hand over the object via std::move and the class has a move constructor, I would expect it to use the move constructor and leave the copy constructor along. But in the end only the copy constructor is called.

Can someone tell me why and what I can do to save at least one copy?

Regards

Aucun commentaire:

Enregistrer un commentaire