我有代码,其中要在单独线程中执行的对象派生自具有纯虚拟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);
}
代码编译正常(这是战斗的一半),但“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();
}