boost thread破坏了多态性

Ha1*_*wed 5 c++ boost boost-thread

复制:实现boost :: thread包装器接口时"调用纯虚方法"

我试图使用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;
};
Run Code Online (Sandbox Code Playgroud)

这个类在start()中创建线程,如下所示:

thisThread = new boost::thread(&Thread::run, this);

问题是当我创建一个覆盖run()方法的类时,run()Thread 的方法是由线程调用而不是新run()方法

例如,我有一个扩展Thread的类:

class CmdWorker: public Thread {
public:
    CmdWorker() : Thread() {}
    virtual ~CmdWorker() {}

    void run() { /* deosn't get called by the thread */ }
};
Run Code Online (Sandbox Code Playgroud)

当我做

Thread *thread = new CmdWorker();
thread.start(); //---> calls run() from Thread instead of run() from CmdWorker
Run Code Online (Sandbox Code Playgroud)

但为了更清楚:

thread.run();  calls the correct run from CmdWorker, (run() is virtual from Runnable)
Run Code Online (Sandbox Code Playgroud)

知道为什么会发生这种情况或者如何修复它?

注意:我创建了一个函数(与Thread类无关)

void callRun(Thread* thread) {
    thread->run();
}
Run Code Online (Sandbox Code Playgroud)

并将线程创建更改为:

thisThread = new boost::thread(callRun, this);
Run Code Online (Sandbox Code Playgroud)

在调试时我注意到thread指针指向Thread类型的对象而不是CmdWorker

编辑:

测试用户代码:http://ideone.com/fqMLFhttp://ideone.com/Tmva1

对象似乎被切片(但由于使用了指针,这很奇怪)

没有设法增加它的推动力

Ale*_* C. 3

答案就在这个问题中:

实现 boost::thread 包装器接口时“调用纯虚拟方法”

基本上,当 boost::thread 对象开始运行时,它所运行的对象有时间被删除。

您必须实现一个join在销毁对象之前手动调用的方法。