c++ - boost线程破坏多态性

标签 c++ boost boost-thread

拷贝:"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/fqMLFhttp://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/

相关文章:

C++程序内存计算

c++ - 如果原始像素在新图像中为黑色,则 Qt 绘制蓝色像素

c++ - 从基本类型的 vector 访问派生成员

C++ 如何在可移植代码中处理 tr1 和非 tr1 命名空间?

c++ - Visual C++ Form 项目中的 Boost.asio

c++ - 两个线程都阻塞调用 boost::mutex::lock()

c++ - Boost::mutex - 是否可以将它锁定在一个类函数中并在另一个类函数中解锁?

C++ 等效于 Java static final String

gcc - boost::program_options 给出 malloc 错误

c++ - 在使用 boost 预处理器序列时避免扩展宏