Sto cercando di creare un oggetto service
che può essere eseguito (ad esempio, eseguire la funzione run()
) in un thread separato. Questo è l'oggetto del servizioEreditarietà C++: chiamata al metodo virtuale quando è stata sovrascritta
#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_;
};
Io sono la creazione di una classe test
che eredita da questa classe astratta e si chiama nella funzione 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;
}
Ora, quando eseguo questo, perché posso ottenere un errore dicendo pure virtual function called
? La funzione run()
è chiaramente sovrascritta nella classe test
. Qual è il peggio è che funziona correttamente a volte?
$ ./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
Cosa potrebbe andare storto qui?
si sta chiamando la funzione virtuale 'start();' nel costruttore. Questa è la ragione di questo errore. – Jagannath
@Jagannath Questo è perfettamente definito qui e non è un problema. – Barry
No, non lo è. A questo punto, l'oggetto derivato è già costruito. –