Search code examples
c++multithreadingrvalue-referencevisual-c++-2012stdthread

Movable parameters in std::thread constructor (Visual C++ 2012)


I run into problem with rvalue references in MSVC 2012.

#include <thread>
#include <string>
#include <future>

void foo(std::promise<std::string> &&prms) { /* some code */ }

int main() {
  std::promise<std::string> prms;
  // std::future<std::string> ftr = prms.get_future();
  std::thread th(&foo, std::move(prms));

  // some other code
}

Compiler says: error C2664: 'void (std::promise<_Ty> &&)' : cannot convert parameter 1 from 'std::promise<_Ty>' to 'std::promise<_Ty> &&'

Is there my mistake (then how to fix it) or compiler issue (then I'd like to know origin of such behaviour)?


Solution

  • This is a known issue in the Visual C++ 2012 implementation of std::thread. See the following bug on Microsoft Connect:

    std::thread constructor doesn't handle movable object

    The response to that bug states:

    We attempted to fix this during VC11's development, but it exploded horribly and we had to revert the change. As it turns out, std::thread can't be powered by bind(), because thread needs to move its arguments, and bind() is forbidden from doing so (since bound functors should be repeatedly invokable, without their bound arguments being moved-from). So we'll need to reimplement std::thread's ctor to avoid using bind().