Home > OS >  Non-Standard Syntax Error in Thread Constructor
Non-Standard Syntax Error in Thread Constructor

Time:07-12

I'm currently looking at producing a C library. I've not much experience with C and have what is probably a very basic question about class instance method calling.

main.cpp

msgserver m;
std::thread t1(m.startServer, "192.168.50.128", 8081);

msgserver.h

class msgserver
{
public:    
    msgserver() { }
    int startServer(std::string addr, int port);
};

msgserver.cpp

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?

CodePudding user response:

The syntax for a getting a pointer to a member function is &<class name>::<function_name>.

In this case &msgserver::startServer would be the correct expression. 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::thread t1(&msgserver::startServer, std::ref(m), "192.168.50.128", 8081);

or

std::thread t1(&msgserver::startServer, &m, "192.168.50.128", 8081);

CodePudding user response:

Replace

msgserver m;
std::thread t1(m.startServer, "192.168.50.128", 8081);

with the lambda function

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. But that's not how C works.

Completely endorse the recommendation that you get a C book. Now you have lambda functions to add to your list of topics to learn.

  •  Tags:  
  • c
  • Related