2012-04-19 9 views
2
#include <thread> 
#include <cassert> 
#include <iostream> 
#include <string> 
#include <future> 
#include <utility> 

void ThFun(std::promise<std::string>&& prms) 
{ 
    std::string hello = "Hello From Future!\n"; 
    prms.set_value(hello); 
} 

int main() 
{ 
    std::promise<std::string> prms; 
    auto ftr = prms.get_future(); 
    std::thread th(&ThFun, std::move(prms)); 
    std::cout << "Hello from Main\n"; 
    std::string str = ftr.get(); 
    std::cout << str << std::endl; 
    th.join(); 

    return 0; 
} 

このビルドエラーが発生します。なぜstd :: moveがここで失敗しているのでしょうか?

1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional(1140):  error C2664: 'void (std::promise<_Ty> &&)' : cannot convert parameter 1 from 'std::promise<_Ty>' to 'std::promise<_Ty> &&' 
1>   with 
1>   [ 
1>    _Ty=std::string 
1>   ] 
1>   You cannot bind an lvalue to an rvalue reference 
1>   c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional(1140) : while compiling class template member function 'void std::_Bind<_Forced,_Ret,_Fun,_V0_t,_V1_t,_V2_t,_V3_t,_V4_t,_V5_t,<unnamed-symbol>>::operator()(void)' 
1>   with 
1>   [ 
1>    _Forced=true, 
1>    _Ret=void, 
1>    _Fun=void (__cdecl *const)(std::promise<std::string> &&), 
1>    _V0_t=std::promise<std::string>, 
1>    _V1_t=std::_Nil, 
1>    _V2_t=std::_Nil, 
1>    _V3_t=std::_Nil, 
1>    _V4_t=std::_Nil, 
1>    _V5_t=std::_Nil, 
1>    <unnamed-symbol>=std::_Nil 
1>   ] 
1>   c:\program files (x86)\microsoft visual studio 11.0\vc\include\thread(50) : see reference to class template instantiation 'std::_Bind<_Forced,_Ret,_Fun,_V0_t,_V1_t,_V2_t,_V3_t,_V4_t,_V5_t,<unnamed-symbol>>' being compiled 
1>   with 
1>   [ 
1>    _Forced=true, 
1>    _Ret=void, 
1>    _Fun=void (__cdecl *const)(std::promise<std::string> &&), 
1>    _V0_t=std::promise<std::string>, 
1>    _V1_t=std::_Nil, 
1>    _V2_t=std::_Nil, 
1>    _V3_t=std::_Nil, 
1>    _V4_t=std::_Nil, 
1>    _V5_t=std::_Nil, 
1>    <unnamed-symbol>=std::_Nil 
1>   ] 
1>   c:\users\jim\documents\visual studio 11\projects\promisesandfutures \promisesandfutures\main.cpp(18) : see reference to function template instantiation 'std::thread::thread<void(__cdecl *)(std::promise<_Ty> &&),std::promise<_Ty>>(_Fn,_V0_t &&)' being compiled 
1>   with 
1>   [ 
1>    _Ty=std::string, 
1>    _Fn=void (__cdecl *)(std::promise<std::string> &&), 
1>    _V0_t=std::promise<std::string> 
1>   ] 

私はVC11を使用しています。エラーは、左辺値をバインドすることはできませんが、私はstd :: moveを使用して右辺値にしています。

ありがとうございました。

std :: refは正常に動作します。

答えて

7

VC11がgcc 4.7より前にgccと同じ間違いをしたように見せかけるエラーメッセージから、std::threadの内部でstd::bindを使用しています。 std::bindでは、引数がコピー可能であることが必要ですが、std::threadではコピーできません。つまり、std::promiseのような移動専用の型は、引数としてスレッドに渡すことはできません。

実際には、gcc 4.7、またはMSVC 2010と私のjust::thread implementation of the C++11 thread libraryで動作しますが、ネイティブライブラリ(gcc 4.6も同様に:: threadを使用すると動作します)を使用してgcc 4.6で同様のエラーメッセージが表示されません。

+0

msftにバグとして投稿します。ありがとう。 – Tavison

関連する問題