如下C++代码,Mybase继承Base类,重写了虚函数printmsg, 并在父类中将printmsg放在线程中循环执行。
在main函数中,期望init执行后,将循环打印 mybase print,而实际只打印了一次,其它都是父类的base print。
#include <thread>
#include <iostream>
#include <chrono>
using namespace std;
class Base {
public:
Base() {
}
~Base()
{
if (t_process_.joinable()) t_process_.join();
}
virtual void init()
{
thread t(bind(&Base::process, this));
t_process_ = move(t);
}
virtual void process() {
while (1)
{
printmsg();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
virtual void printmsg() { cout << "base print" << endl; }
private:
thread t_process_;
};
class Mybase : public Base {
public:
virtual void printmsg() override { cout << "mybase print" << endl; }
};
int main(int argc, char* argv[])
{
Mybase obj;
obj.init();
return 0;
}
原因是虽然父类子线程中有永久循环,并将线程join到主线程中,但只能维持Base不被析构,而Mybase obj在 obj.init()后即析构了。因此子类Mybase的printmsg不再有效。