[英]Non-Standard Syntax Error in Thread Constructor
I'm currently looking at producing a C++ library.我目前正在考虑制作一个 C++ 库。 I've not much experience with C++ and have what is probably a very basic question about class instance method calling.我对 C++ 没有太多经验,并且可能有一个关于类实例方法调用的非常基本的问题。
msgserver m;
std::thread t1(m.startServer, "192.168.50.128", 8081);
class msgserver
{
public:
msgserver() { }
int startServer(std::string addr, int port);
};
int msgserver::startServer(string addr, int port)
This code results in:此代码导致:
[C3867] 'msgserver::startServer': non-standard syntax; use '&' to create a pointer to member
I know i can fix the compiler error by making this method static but I'm unsure if that is a requirement imposed by the fact it's being called in a thread constructor (which doesn't allow the parens on the call signature) or if I need to figure out the syntax.我知道我可以通过将此方法设为静态来修复编译器错误,但我不确定这是否是在线程构造函数中调用它(不允许调用签名上的括号)这一事实所强加的要求,或者如果我需要弄清楚语法。
I've read around this and it's actually left me a bit more confused that when I started.我已经阅读了这个,它实际上让我在开始时更加困惑。 It seems any fix I apply like:似乎我应用的任何修复都像:
int &msgserver::startServer(string addr, int port)
or
std::thread t1(&m.startServer, "192.168.50.128", 8081);
Is actually illegal syntax according to the compiler.根据编译器实际上是非法语法。
How can I call this as an instance method?我如何将其称为实例方法? Or is actually a good idea to start a thread running in the background on a static function?或者在静态函数上启动在后台运行的线程实际上是一个好主意?
The syntax for a getting a pointer to a member function is &<class name>::<function_name>
.获取成员函数指针的语法是&<class name>::<function_name>
。
In this case &msgserver::startServer
would be the correct expression.在这种情况下&msgserver::startServer
将是正确的表达式。 Since std::invoke
is used on the background thread, you need to pass the object to call the function for as second constructor parameter for std::thread
, either wrapped in a std::reference_wrapper
or by passing a pointer:由于在后台线程上使用了std::invoke
,因此您需要传递对象以调用函数作为std::thread
的第二个构造函数参数,或者包装在std::reference_wrapper
或通过传递指针:
std::thread t1(&msgserver::startServer, std::ref(m), "192.168.50.128", 8081);
or或者
std::thread t1(&msgserver::startServer, &m, "192.168.50.128", 8081);
Replace代替
msgserver m;
std::thread t1(m.startServer, "192.168.50.128", 8081);
with the lambda function使用lambda 函数
msgserver m;
std::thread t1([=](std::string addr, int port){ m.startServer(addr, port); },
"192.168.50.128", 8081);
I'm guess that you expected your version to do what the lambda function does by some kind of C++ magic.我猜你希望你的版本通过某种 C++ 魔法来完成 lambda 函数所做的事情。 But that's not how C++ works.但这不是 C++ 的工作方式。
Completely endorse the recommendation that you get a C++ book.完全赞同你获得一本 C++ 书籍的建议。 Now you have lambda functions to add to your list of topics to learn.现在,您可以将 lambda 函数添加到要学习的主题列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.