2017-04-06 40 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

謝謝!這是問題所在。我沒有靜態創建對象,而是創建了對象,並且它可以工作。 –