简体   繁体   中英

pure virtual method called in thread of concrete class

I have a problem with virtual methods in C++ on a multithreading context (Linux).

This next example points out my problem:

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;
}

When the line ptr->func() is executed, the following error appears:

pure virtual method called terminate called without an active exception

Can someone tell me why the pure virtual method is being called instead of the overrided method?

Concrete2 is created on the stack and is destroyed as soon as run is called.

The spawned thread does not keep obj alive.

Your thread function is trying to dereference a destroyed object, aka a dangling pointer , which constitutes undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM