13
votes

The following gives me an error in visual studio 2012.

void do_something(std::unique_ptr<int> i);
std::unique_ptr<int> i(new int);
std::thread(do_something, std::move(i));

Error 3 error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>' c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional 1152 1 scratch It is helpfully(!) pointing at this definition in functional: _VARIADIC_EXPAND_0X(_CLASS_BIND, , , , )

This is fine:

do_something(std::move(i));

What am I doing wrong?

1
I am told that GCC 4.6 had a similar bug that was fixed in 4.7: "the std::thread needs to recognise when it's passed an rvalue and move (not copy) it into its internal storage and then should forward it on to the wrapped function as an rvalue again" Thanks to Jon Wakely <stackoverflow.com/users/981959/jonathan-wakely>doctorlove

1 Answers

5
votes

What am I doing wrong?

Almost nothing. In fact, your program is legal and its behavior is well defined.

The compiler error you are getting is necessarily a bug in the implementation of the Standard Library that ships with your compiler, perhaps connected with the fact that VC11 does not support variadic templates, and the macro-based machinery used to fake them is not perfect.

This said, even if your program did compile, you would still have to join your thread or detach from it before the std::thread RAII wrapper gets destroyed - an exception is thrown if the destructor of std::thread is invoked while the encapsulated thread is still running (unless it was detached).