C++11 std::thread giving error: no matching function to call std::thread::thread

Roman Rdgz picture Roman Rdgz · Sep 27, 2012 · Viewed 21.1k times · Source

I'm testing c++11 threads with this code, but when creating the thread, I'm having the error no matching function for call to 'std::thread::thread()'.

It's like if there was something wrong with the function I'm giving to std::thread ctr, but I don't see how it's wrong. It is incompleted, but it looks right to me:

Header:

#ifndef CONNECTION_H
#define CONNECTION_H

#include <thread>
#include <mysql++.h>

class Connection
{
public:
    Connection(std::string mysqlUser, std::string mysqlPassword);
    ~Connection();

private:
    std::string mysqlUser;
    std::string mysqlPassword;
    std::string mysqlIP;
    int mysqlPort;

    mysqlpp::Connection mysqlConnection;
    std::thread connectionThread;

    void threadLoop();
};

#endif // CONNECTION_H

Source:

#include "connection.h"

Connection::Connection(std::string mysqlUser, std::string mysqlPassword)
{
    this->mysqlUser     = mysqlUser;
    this->mysqlPassword = mysqlPassword;
    this->mysqlIP       = "localhost";    //default
    this->mysqlPort     = 3306;           //default

    //Launch thread
    std::thread connectionThread(threadLoop);

}

Connection::~Connection(){
    mysqlConnection.disconnect();
}

void Connection::threadLoop(){
    //Connect to mySQL database
    mysqlConnection = new mysqlpp::Connection(false);

    if(mysqlConnection.connect(NULL, mysqlIP.c_str(), mysqlUser.c_str(), mysqlPassword.c_str(), mysqlPort)){
        std::string consulta = "SELECT * FROM 'Coordinates'";
        mysqlpp::Query query = mysqlConnection.query(consulta);
        mysqlpp::StoreQueryResult res = query.store();
        query.reset();

    }

    while(true){
        // Stuff
    }
}

Answer

Pete Becker picture Pete Becker · Sep 27, 2012

The problem is that threadLoop is a member function, but there is no object for it to be applied to. Just guessing:

std::thread connectionThread(&Connection::threadLoop, this);

But that's just the syntactic issue; there's a logic problem, too: that line creates a local object of type std::thread that goes away when the function returns. Its destructor will call std::terminate() because the thread has not been joined. Most likely, this was supposed to attach a thread to the connectionThread member. To do that:

std::thread thr(threadLoop, this);
std::swap(thr, connectionThread);