C ++继承:在重写时调用虚方法

时间:2015-07-17 23:24:25

标签: c++ multithreading inheritance virtual-functions

我正在尝试构建一个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 calledrun()类中明确覆盖了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

这里可能出现什么问题?

1 个答案:

答案 0 :(得分:10)

一步一步地继续:

1)构建对象。

2)执行以下代码:

if (started_.load() == false) {
  started_ = true;
  thread_ = std::thread([&] () {
    run();
  });
}

父线程立即返回main()立即退出并销毁您的对象。

这是你的错误:

  • 在父线程终止进程之前,无法保证在start()中启动的线程将在上面调用run()。子线程和父线程同时运行。

因此,每隔一段时间,父线程将在子线程开始之前销毁对象,并调用run()。

此时,调用run()方法的对象已被销毁。

未定义的行为。

你偶尔会遇到的断言是这种未定义行为的可能结果。