WRT下面的代码,我发现编译问题,尝试通过调用另一个对象中的成员函数来创建一个线程。
th = std::thread(&AbcSFriend::S2F,this,friendObj);
是导致编译错误的罪魁祸首。如果我删除此行iit编译好。
class AbcSFriend
{
public:
void S2F(Abc* ptr)
{}
};
class Abc
{
public:
std::thread th;
AbcSFriend frinedObj;
void FL()
{
th = std::thread(&AbcSFriend::S2F,this,friendObj);
}
};
当UDT包含零大小的数组时,无法生成copy-ctor或copy-assignment运算符1> C:\ Program Files(x86)\ Microsoft Visual Studio 12.0 \ VC \ include \ functional(1149):error C2664:'eUserErrorCode std: :_Pmf_wrap :: operator()(_ Farg0&,abc *)const':无法将参数2从'AbcSFriend'转换为'Abc *'1> 1> [1> _Farg0 = AbcSFriend 1>] 1>没有可以执行此转换的用户定义转换运算符,或者无法调用运算符1> C:\ Program Files(x86)\ Microsoft Visual Studio 12.0 \ VC \ include \ functional(1137):参见函数模板实例化'_UserErrorCode std :: _ Bind,Abc *,AbcSFriend> :: _ Do_call <,0x00,0x01>(std :: tuple <>,std :: _ Arg_idx <0x00 ,0x01>)'正在编译1> C:\ Program Files(x86)\ Microsoft Visual Studio 12.0 \ VC \ include \ functional(1137):参见函数模板实例化'_UserErrorCode std :: _ Bind,Abc *,AbcSFriend> :: _ Do_call <,0x00,0x01>(std :: tuple <>,std :: _ Arg_idx <0x00,0x01>)'正在编译1> C:\ Program Files(x86)\ Microsoft Visual Studio 12.0 \ VC \ include \ thr / xthread(195):参见函数模板实例化'_UserErrorCode std :: _ Bind,Abc *,AbcSFriend> :: operator()<>(void)'正在编译1> C:\ Program Files(x86)\ Microsoft Visual Studio 12.0 \ VC \ include \ thr / xthread(195):请参阅函数模板的参考实例化'_UserErrorCode std :: _ Bind,Abc *,AbcSFriend> :: operator()<>(void)'正在编译1> C:\ Program Files(x86)\ Microsoft Visual Studio 12.0 \ VC \ include \ thr / xthread( 192):在编译类模板成员函数时'unsigned int std :: _ LaunchPad <_Target> :: _ Run(std :: _ LaunchPad <_Target> *)'1> 用1> [1> _Target = std :: _ Bind,Abc *,AbcSFriend> 1>] 1> C:\ Program Files(x86)\ Microsoft Visual Studio 12.0 \ VC \ include \ thr / xthread(187):参见函数模板实例化'unsigned int std :: _ LaunchPad <_Target> :: _ Run(std :: _ LaunchPad <_Target> *)'正在编译1> 1> [1> _Target = std :: _ Bind,Abc *,AbcSFriend> 1>] 1> C:\ Program Files(x86)\ Microsoft Visual Studio 12.0 \ VC \ include \ thr / xthread(205):参见类模板实例化'std :: _ LaunchPad <_Target>'正在编译1> 1> [1> _Target = std :: _ Bind,Abc *,AbcSFriend> 1>] 1> C:\ Program Files(x86)\ Microsoft Visual Studio 12.0 \ VC \ include \ thread(49):参见函数模板实例化'void std: :_Launch,Abc *,AbcSFriend >>(_ Thrd_t *,_ Target &&)'正在编译1> 1> [1> _Target = std :: _ Bind,Abc *,AbcSFriend> 1>] 1> .... \ Sources \ SOMEPLACESource.cpp(254):参见函数模板实例化'std :: thread :: thread(_Fn &&,Abc) const &&,AbcSFriend&)'正在编译1> 1> [1> _Fn = eUserErrorCode(__ cdecl AbcSFriend ::)(Abc *)
frinedObj
(在AbcSFriend frinedObj;)
不是
friendObj
(在th = std :: thread(&AbcSFriend :: S2F,this,friendObj);)。
修复拼写。
正如'Maxim Egorushkin'所说,试试:
class AbcSFriend
{
public:
void S2F(class Abc* ptr);
};
class Abc
{
public:
std::thread th;
AbcSFriend friendObj;
void FL()
{
th = std::thread(&AbcSFriend::S2F, &friendObj, this);
}
};
我认为正确的参数顺序是:
th = std::thread(&AbcSFriend::S2F, &friendObj, this);
改变成员th
和friendObj
的声明的顺序也是有道理的,因为目前friendObj
在th
在th
被摧毁之后使用friendObj
开启了friendObj
的可能性。首先声明friendObj
,最后声明th
。