使用带有纯虚函数的C++ 11线程

Jam*_*mes 8 c++ multithreading c++11 visual-studio-2012

我有代码,其中要在单独的线程中执行的对象派生自具有纯虚Run函数的基类.我无法获得以下(简化的测试代码)来运行新线程.

#include <iostream>
#include <thread>
#include <functional>

class Base {
public:
    virtual void Run() = 0;
    void operator()() { Run(); }
};

class Derived : public Base {
public:
    void Run() { std::cout << "Hello" << std::endl; }
};

void ThreadTest(Base& aBase) {
    std::thread t(std::ref(aBase));
    t.join();
}

int main(/*blah*/) {
    Base* b = new Derived();
    ThreadTest(*b);
}
Run Code Online (Sandbox Code Playgroud)

代码编译很好(这是战斗的一半),但"Hello"永远不会打印.如果我做错了什么我会在某个时候发现运行时错误.我正在使用gcc.

编辑:上面的代码无法在VS2012上编译,具有: error C2064: term does not evaluate to a function taking 0 arguments

你需要使用lambda代替std::ref,即

void ThreadTest(Base& aBase)
{
    std::thread t([&] ()
    {
        aBase.Run();
    });
    t.join();
}
Run Code Online (Sandbox Code Playgroud)

Cyr*_* Ka 3

您需要将 -pthread 添加到 g++ 命令行,如类似问题的答案中所述: https: //stackoverflow.com/a/6485728/39622