拷贝:"pure virtual method called" when implementing a boost::thread wrapper interface
我正在尝试使用 boost 线程创建一个更加面向对象的线程版本。
所以我创建了一个 Thread 类:
class Thread {
public:
Thread() {}
virtual ~Thread() { thisThread->join(); }
void start() { thisThread = new boost::thread(&Thread::run, this); }
virtual void run() {};
private:
boost::thread *thisThread;
};
此类在 start() 中创建线程 像这样:
thisThread = new boost::thread(&Thread::run, this);
问题是,当我创建一个覆盖 run()
方法的类时,Thread 中的 run()
方法由线程而不是新方法调用run()
方法
例如我有一个扩展线程的类:
class CmdWorker: public Thread {
public:
CmdWorker() : Thread() {}
virtual ~CmdWorker() {}
void run() { /* deosn't get called by the thread */ }
};
当我这样做
Thread *thread = new CmdWorker();
thread.start(); //---> calls run() from Thread instead of run() from CmdWorker
但只是为了更清楚:
thread.run(); calls the correct run from CmdWorker, (run() is virtual from Runnable)
知道为什么会发生这种情况或如何解决吗?
注意: 我创建了一个函数(与 Thread 类无关)
void callRun(Thread* thread) {
thread->run();
}
并将线程创建更改为:
thisThread = new boost::thread(callRun, this);
调试时我注意到 thread
指针指向 Thread 类型的对象而不是 CmdWorker
编辑:
测试用例代码:http://ideone.com/fqMLF 和 http://ideone.com/Tmva1
对象似乎被切片了(但这很奇怪,因为使用了指针)
没能给它增加动力
最佳答案
答案就在那个问题中:
"pure virtual method called" when implementing a boost::thread wrapper interface
基本上,当 boost::thread 对象开始运行时,它运行的对象具有 删除的时间。
您必须在销毁对象之前实现手动调用的 join
方法。
关于c++ - boost线程破坏多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7391920/