2017-04-06 171 views
0

我在多线程上下文(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 

谁能告诉我,为什么纯虚方法被调用而不是被过度使用的方法?

+0

你在哪里声明'func'是虚拟的? –

+0

@ G.M。无关紧要,它是由于被称为相同的,但是如果不是,关键字override可能有助于缩小范围。 – Paul

+0

我认为相关:https://stackoverflow.com/questions/7381757/c-terminate-called-without-an-active-exception – rsp

回答

0

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

生成的线程不会保持obj有效。

您的thread函数试图取消引用被破坏的对象,也就是dangling pointer,这构成未定义的行为。

+0

谢谢!这是问题所在。我没有静态创建对象,而是创建了对象,并且它可以工作。 –