samedi 29 juillet 2017

Invoking a pure virutal method within a thread

I have the requirement of invoking a pure virtual method implementation when spawning a thread from within a based class method as shown below.

#include <iostream>

class Foo {
  private:
    std::thread tr;

  public:
    virtual void baz() = 0;
    void foo() {
      this->tr = std::thread([=] { this->baz(); });
    }

};

class Bar : public Foo {
  public:
    void baz() {
      std::cout << "In baz" << "\n";
    }

};

Main class...

#include <thread>
#include "test.hpp"

int main(int argc, char* argv[]) {
  Bar b;
  b.foo();
}

But it fails with the message

terminate called without an active exception

pure virtual method called

The message "pure virtual method called" appears only in some of the failure messages. What am I doing wrong? Is it something related to Bar or the thread getting improperly destructed?

Aucun commentaire:

Enregistrer un commentaire