I launched a thread in based thread. There is a pure virtual function called in this thread. I implement it in the derived class.
#include <iostream>
#include <memory>
#include <thread>
struct Base {
std::unique_ptr<std::thread> th;
virtual void foo() = 0;
void bar() {
th = std::make_unique<std::thread>(
[this](){
foo();
}
);
}
virtual ~Base(){
th->join();
}
};
struct Derived : public Base {
virtual void foo() override {
std::cout << "impl in derived" << std::endl;
}
};
int main() {
Derived d;
d.bar();
return 0;
}
However, in these codes, the derived object will decontruct before the base object.
pure virtual method called
terminate called without an active exception
Aborted (core dumped)
How to control the destruction order in this situation?