user3382749
user3382749

Reputation: 41

std::thread and move in visual studio 2013

I have an only-moveable class and a function who takes an object of this class by value. The functions is called in a new thread:

void foo(MyClass a) {}

int main()
{
   MyClass a;
   std::thread t(&foo, std::move(a));
}

I get a compiler error, because of the missing copy-constructor of MyClass (I deleted him) and if I implement him the copy-constructor is called.

Obviously this is a bug and it compiles without copy-constructor in gcc. Are there any workarounds?

Upvotes: 4

Views: 1071

Answers (1)

ComicSansMS
ComicSansMS

Reputation: 54589

If the method needs ownership of a, pass it through the heap, preferably in a shared_ptr:

void foo(std::shared_ptr<MyClass> a) {}
 [...]

auto a_ptr = std::make_shared<MyClass>();
std::thread t(foo, a_ptr);

Otherwise just pass it by reference:

void foo(MyClass& a) {}
 [...]

MyClass a;
std::thread(foo, std::ref(a));

Upvotes: 2

Related Questions