【发布时间】:2011-09-12 17:59:13
【问题描述】:
重复:"pure virtual method called" when implementing a boost::thread wrapper interface
我正在尝试使用 boost 线程创建一个更面向对象的线程版本。
所以我创建了一个线程类:
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() 方法
例如,我有一个扩展 Thread 的类:
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
对象似乎被切片了(但这很奇怪,因为使用了指针)
没能增加动力
【问题讨论】:
-
这个问题我不清楚!
-
没有足够的代码。我看不出你会如何使用这种结构。
-
仅供参考
std::thread即将到来。boost::thread到底有什么问题? -
你在构造函数中碰巧调用了
start吗? -
@Hallowed:好的,我设法让它在我的机器上编译,令人惊讶的是,我观察到了你的行为。让我开始吧。
标签: c++ boost boost-thread