Threads in Constructor in C++ [duplicate] - c++

This question already has answers here:
Start thread with member function
(5 answers)
Closed 6 years ago.
I'm trying to create threads in a constructor of a class that will run a couple of functions inside that class, I've tried this:
ServerLogic::ServerLogic(SOCKET sock)
{
this->sock = sock;
this->dispatchThread = new std::thread(this->dispatchMessage);
}
void ServerLogic::dispatchMessage(){
/*
* this function will handle the connetions with the clients
*/
char recievedMsg[1024];
int connectResult;
//receive data
while (true){
connectResult = recv(this->sock, recievedMsg, sizeof(recievedMsg), 0);
//in case everything good send to diagnose
if (connectResult != SOCKET_ERROR){
this->messagesToDiagnose.push(std::string(recievedMsg));
}
else{
/*
* destructor
*/
}
}
}
but it's giving me an errors:
'ServerLogic::dispatchMessage': function call missing argument list; use '&ServerLogic::dispatchMessage' to create a pointer to member.
IntelliSense: function "std::thread::thread(const std::thread &)" (declared at line 70 of "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\thread") cannot be referenced -- it is a deleted function.

I think that the error message is basically telling you what to do. Consider the following code (which is problematic, but just serves to illustrate the point):
#include <thread>
class foo
{
public:
foo()
{
std::thread(&foo::bar, this);
}
void bar()
{
}
};
int main()
{
foo f;
}
To specify a member function, use
std::thread(&foo::bar, this);

Related

error: cannot declare pointer to ‘void’ member [duplicate]

This question already has answers here:
Explanation of function pointers
(4 answers)
Closed 8 months ago.
I have the following scenario: I have a third party library and a header associated with it, that I'm using in my project. I completed my project and now I'm unit testing my code and I want to use a stub library, created by myself, for the third party library.
The header for the third party library contains structures that looks like this:
typedef struct{
int (*init)(int * var);
void (*close)(void);
} AInterface
To create my stub version, I created a .cpp file, in which I include the header, and started to implement it like this:
int AInterface::*init(int* var)
{
return 0;
}
void AInterface::*close(void)
{}
But when I compile my code I get the following error: "stub.cpp:76:33: error: cannot declare pointer to ‘void’ member
void AInterface::*close(void)"
I have searched the internet but with no success.
My questions are:
what I am doing wrong here?
is there another way to implement the stub?
I have also tried to implement the stub like this:
int initAInterface(int * var);
int (AInterface::*init)(int * var) = &initAInterface;
int initAInterface(int* var)
{
return 0;
}
But I get the following error:
error: cannot convert ‘int (*)(int*)’ to ‘int (AInterface::*)(int*)’ in initialization
int (AInterface::*init)(int* var) = &initAInterface;
Also I have no main in my stub .cpp file.
Those are function pointers and expect you to give static functions to them, then pass the struct to the library
//#################################################################
//Library header
typedef struct {
int (*init)(int* var);
void (*close)(void);
} AInterface;
//#################################################################
//A CPP file somewhere
//You might need extern "C" if you're mixing C and C++
#include "LibraryHeader.h"
int myInitFuction(int* var)
{
std::cout << "I wrote the init function for this" << std::endl;
return 0;
}
void myCloseFunction(void){
std::cout << "I wrote the close function for this" << std::endl;
}
//Or some other function doesn't need to be main if it's not the entry point
int main()
{
AInterface myInterface;
myInterface.init = myInitFuction;
myInterface.close = myCloseFunction;
SomeLibraryFuction(&myInterface);
}

How do I run a member function on a thread? [duplicate]

This question already has answers here:
Start thread with member function
(5 answers)
Closed 3 years ago.
When I compile the code below I get the following error. help me...!
Errors:
Error C2276 '&': illegal operation on bound member function expression
Error C3867 'CCore::Run': non - standard syntax; use '&' to create a pointer to member
I'm not sure if the program gives me an error.
I want to run the "Run" function of the Core class.
Core.cpp file contains only the functions created by the compiler.
I'm learning English so I'm not good yet. So please understand that the whole code.
// main.cpp
#include "Core.h"
#include <thread>
int main()
{
// The conditions below have been success
if (CCore::GetInstance().Init())
{
// The code below fails to compile.
// Error C3867 'CCore::Run': non - standard syntax; use '&' to create a pointer to member
thread main_thread(CCore::GetInstance().Run);
// Error C2276 '&': illegal operation on bound member function expression
thread main_thread(&CCore::GetInstance().Run);
main_thread.join();
}
return 0;
}
// Core.h
#pragma once
#include "Singleton.h"
#include <iostream>
using namespace std;
class CCore : public Singleton<CCore>
{
public:
CCore();
~CCore();
bool Init();
void Run();
};
// Singleton.h
#pragma once
template<typename T>
class Singleton
{
protected:
Singleton()=default;
~Singleton()=default;
public:
static T& GetInstance()
{
static T instance;
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton) = delete;
};
The compiler tells you the problem: Run() isn't a free function. It's a method, i.e. a function bound to an instance of an object. You have several options, but generally you either let the compiler synthesize a runnable for you, or write a free function yourself:
Let the compiler do all the work: guess what, it can make singletons for you so how cool is that?!
std::thread main_thread([]{
static CCore myCore;
myCore.Run();
});
You want to access that core? Sure!
std::future<CCore*> coreWhenDone = std::async([]{
static CCore myCore;
myCore.Run();
return &myCore;
});
Better yet, the core would provide some result, so that instead of accessing it directly when it's done, you could get its result (e.g. an int or std::vector<double> or whatever that core is computing)/
Let the compiler do some of the work:
std::thread main_thread([]{ CCore::GetInstance().Run(); });
Split the work between yourself and the compiler:
std::thread main_thread(std::bind(&CCore::Run, &CCore::GetInstance()));
Do all the work yourself:
void runCoreRun() {
CCore::GetInstance().Run();
}
...
std::thread main_thread(&runCoreRun);

singleton in c++ compile error [duplicate]

This question already has answers here:
Undefined reference to static class member
(9 answers)
Closed 7 years ago.
I tried to make the following singleton class in C++
#pragma once
#include "stdafx.h"
#include <iostream>
class God
{
private:
static God* firstObject;
God()
{
if (firstObject != NULL)
firstObject = this;
}
public:
static God* BuildGod()
{
if (firstObject != NULL)
return firstObject;
else {
God();
return firstObject;
}
}
};
and then use it like so
God* a = God::BuildGod();
Unfortunatley, it won't even compile and it returned the following errors:
LNK2001 unresolved external symbol "private: static class God * God::firstObject" (?firstObject#God##0PAV1#A)
LNK1120 1 unresolved externals
You actually have a worse problem than the build error, because you create a temporary object, and save a pointer to it to be used.
The statement
God();
creates a temporary object, and in the constructor you save a pointer to this temporary object in firstObject which you then return. Using that pointer will then lead to undefined behavior.
One of the usual ways of creating a singleton in C++ would be something like this:
class God
{
public:
static God& get_instance() {
{
static God instance; // This is THE instance
return instance;
}
private:
God() {}
};
A static member of a class has to be defined outside the class, like
class God
{
...
};
God* God::firstObj;
Just beware that having the definition in a header file and including it mamy times calls for trouble.

Function pointer in c++ class [duplicate]

This question already has answers here:
get function member address
(2 answers)
Closed 8 years ago.
I am trying to use function pointer in a c++ class but got an error.
#include <cstdio>
#include <iostream>
using namespace std;
class abc{
public:
void hello(){
printf("Hello world\n");
}
abc(){
void (*hw)(void);
hw = &hello;
hw();
}
}
int main()
{
abc ab;
return 0;
}
Error
error: cannot convert ‘void (abc::*)()’ to ‘void (*)()’ in assignment
But the following code works for me which is in code base. Can anyone please help me to find out the difference?
void hello(){
printf("Hello world\n");
}
int main()
{
void (*hw)(void);
hw = &hello;
hw();
return 0;
}
Function pointers are (unfortunately) completely different from method pointers, as the error is trying to indicate. This is because the object that the method works on needs to be passed in somehow, which is what makes methods fundamentally different from functions in the first place (and obviously affects how the call is done through the pointer). Method pointers are not even always the same size (and can be significantly larger than a function pointer) when multiple/virtual inheritance comes into play.
You need to declare a method pointer, and call it on behalf of an object of the right type using one of the esoteric .* or ->* operators:
class abc {
public:
void hello(){
printf("Hello world\n");
}
abc() {
void (abc::*hw)();
hw = &abc::hello;
(this->*hw)(); // or (*this.*hw)()
}
}

passing functor to boost::thread failed in visual studio 2010 [duplicate]

This question already has answers here:
Why is there no call to the constructor? [duplicate]
(3 answers)
Closed 8 years ago.
This simple code won't compile:
#include <cstdio>
#include <boost/thread.hpp>
struct ftor{
void operator()(){ printf("Hello"); }
};
int main()
{
boost::thread th( ftor() );
th.join(); //<--- error C2228: left of '.join' must have class/struct/union
}
But, following code well compiled:
#include <cstdio>
#include <boost/thread.hpp>
struct ftor{
void operator()(){ printf("Hello"); }
};
int main()
{
ftor f;
boost::thread th( f );
th.join();
}
Q: What's problem with #1 code ?
I use visual studio 2010 .
Update:
codepade http://codepad.org/r5Aok406 shows more informative error:
Line 19: error: request for member 'join' in 'th', which is of non-class type 'mythread ()(ftor (*)())'
boost::thread th( ftor() );
th is declared as a function that returns boost::thread, and takes a function pointer ftor(*)() as input parameter.
To avoid this, either use C++11's new initialization syntax,
boost::thread th{ ftor() };
Or add a parathesis around the ftor().
boost::thread th( (ftor()) );
This is actually one of the well-known c++ glitches. The cause of this problem is for C compatibility.
struct TEST;
TEST a(); //well defined in c, a is a function that returns TEST
C++ has to be compatible with C, so Test a() must be a function, but not declare a as a TEST instance and call its default constructor!