vendredi 20 avril 2018

Sleep affecting which virtual member function is called by std::thread?

I am unsure if this is expected behavior in c++11. Here is an example of what I found.

#include <iostream>
#include <thread>
using namespace std;

class A {
public:
    virtual void a() = 0;
    thread t;
    A() : t(&A::a, this) {}
    virtual ~A() {
        t.join();
    }
};

class B : public A {
public:
    virtual void a() {
        cout << "B::a" << endl;
    }
};

int main() {
    B b;
    this_thread::sleep_for(chrono::seconds(1));
}

When compiled and run

$ g++ -std=c++11 -pthread test.cpp -o test
$ ./test
B::a
$

But when the sleep is removed...

int main() {
    B b;
    //this_thread::sleep_for(chrono::seconds(1));
}

something strange happens

$ g++ -std=c++11 -pthread test.cpp -o test
$ ./test
pure virtual method called
terminate called without an active exception
Aborted (core dumped)
$

Could this be a bug?

Aucun commentaire:

Enregistrer un commentaire