作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试等待线程在纯虚拟类的析构函数中死亡。代码编译得很好,而且看起来很有意义。但是运行时出现如下错误:
pure virtual method called
terminate called without an active exception
Aborted (core dumped)
这是我的程序:
#include <boost/thread.hpp>
#include <iostream>
class Test {
protected:
int x;
boost::thread th;
public:
Test(void): x(10) {};
~Test(void);
virtual void operator()(void);
void run(void);
virtual void a(void) = 0;
void wait(void);
};
Test::~Test(void) {
this->wait();
}
void Test::operator()(void) {
this->a();
x += 10;
std::cout << "Current Value: " << x << std::endl;
}
void Test::run(void) {
this->th = boost::thread(&Test::operator(), this);
}
void Test::wait(void) {
this->th.join();
}
class Test1 : public Test {
public:
virtual void a(void);
};
void Test1::a(void) {
x--;
}
main() {
Test1 test;
test.run();
//test.wait();
}
预期结果是 19。我可以通过在对象离开作用域而不是进入作用域之前在 main()
中调用 Test::wait()
来得到它析构函数。当从 Test
中删除纯虚拟方法 a()
时,不会发生异常。
我的问题是:
Test::a()
不在析构函数的调用链中,错误指的是哪个虚方法?我猜一个答案就是另一个答案......
附言以防万一,我在 Arch Linux,内核版本 3.17.2-1 上运行 g++ (GCC) 4.9.1 20140903(预发布) 在 GNU bash , 版本 4.3.30(1)-发布
最佳答案
问题与问题有关,当您从构造函数/析构函数调用虚函数时。在这种情况下,从基类析构函数调用 wait() - Test::~Test()
,这意味着派生类 Test1
已经被析构并且虚拟表已更新为基类测试
。看起来像单独线程中的虚拟调用在那之后发生,你得到纯虚拟方法调用。所以行为就像你从 Test
的析构函数中间接调用 a()
。
当您显式调用 wait() 时,它会在 test1
实例被销毁之前等待并且工作正常。
与此问题无关,类 Test 的 dtor 应该是虚拟的,因为您有虚拟方法。
关于c++ - 在纯虚类的析构函数中等待线程死亡导致运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26789492/
我是一名优秀的程序员,十分优秀!