在具体类的线程中调用的纯虚方法

时间:2017-04-06 10:21:10

标签: c++ multithreading inheritance pure-virtual

我在多线程上下文(Linux)中使用C ++中的虚方法时遇到问题。

下一个例子指出了我的问题:

class Base {

};

class Concrete1: public Base {    //define pure virtual function
    virtual void func() = 0;
}; 

class Concrete2: public Concrete1 {     //override of virtual func
    void func() {}

    void run(){
        //....
        pthread_create(&handle, NULL, Concrete2::thread, static_cast<void*>(this));
    }

    static void* thread(void arg*){
        Concrete2 *ptr = static_cast<Concrete2*>(arg);
        //Concrete1 *ptr = static_cast<Concrete2*>(arg);    // same error 

        while(1){ 
           //....
           ptr->func()
        }
    }
};

int main(){
  Concrete2 obj;
  obj.run();

  pthread_exit(NULL);
  return 0;
}

执行第ptr->func()行时,会出现以下错误:

pure virtual method called terminate called without an active exception

有人能告诉我为什么要调用纯虚方法而不是覆盖方法吗?

1 个答案:

答案 0 :(得分:0)

Concrete2在堆栈上创建,并在调用run后立即销毁。

衍生线程不会使obj保持活跃状态​​。

你的thread函数试图取消引用一个被破坏的对象,即dangling pointer,这构成了未定义的行为。

相关问题