【发布时间】:2015-10-07 18:47:41
【问题描述】:
我正在尝试构建一个 service 对象,该对象可以在单独的线程中运行(即执行它的 run() 函数)。这是服务对象
#include <boost/noncopyable.hpp>
#include <atomic>
#include <thread>
#include <iostream>
class service : public boost::noncopyable {
public:
service() : stop_(false), started_(false) { }
virtual ~service() {
stop();
if (thread_.joinable()) {
thread_.join();
}
}
virtual void stop() { stop_ = true; }
virtual void start() {
if (started_.load() == false) {
started_ = true;
thread_ = std::thread([&] () {
run();
});
}
}
protected:
virtual void run() = 0;
std::atomic<bool> stop_;
std::atomic<bool> started_;
std::thread thread_;
};
我正在创建一个test 类,它继承自这个抽象类并在main() 函数中调用
class test : public service {
public:
test() : service() {
std::cout<< "CTOR" << std::endl;
start();
}
~test() {
std::cout<< "DTOR" << std::endl;
}
protected:
void run() override {
std::cout << "HELLO WORLD" <<std::endl;
}
};
int main() {
test test1;
return 0;
}
现在当我执行此操作时,为什么会收到错误消息 pure virtual function called? run() 函数在 test 类中明显被覆盖。更糟糕的是它有时运行正确?
$ ./a.out
CTOR
DTOR
pure virtual method called
terminate called without an active exception
$ ./a.out
CTOR
DTOR
pure virtual method called
terminate called without an active exception
$ ./a.out
CTOR
DTOR
pure virtual method called
terminate called without an active exception
$ ./a.out
CTOR
DTOR
HELLO WORLD
$ ./a.out
CTOR
DTOR
pure virtual method called
terminate called without an active exception
这里可能出了什么问题?
【问题讨论】:
-
你在构造函数中调用虚函数
start();。这就是这个错误的原因。 -
@Jagannath 这里定义得很好,不是问题。
-
不,不是。至此,派生对象已经构建完成。
标签: c++ multithreading inheritance virtual-functions