KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have code where objects that are intended to execute in separate thread derive from a base class with a pure virtual Run function. I cannot get the following (simplified test code) to run the new thread. #include <iostream> #include <thread> #include <functional> class Base { public: virtual void Run() = 0; void operator()() { Run(); } }; class Derived : public Base { public: void Run() { std::cout << "Hello" << std::endl; } }; void ThreadTest(Base& aBase) { std::thread t(std::ref(aBase)); t.join(); } int main(/*blah*/) { Base* b = new Derived(); ThreadTest(*b); } The code compiles fine (which is half the battle) but "Hello" never gets printed. If I was doing something wrong I'd expect a runtime error at some point. I'm using gcc. Edit: The code above fails to compile on VS2012, with: error C2064: term does not evaluate to a function taking 0 arguments You need to use a lambda instead of std::ref , i.e. void ThreadTest(Base& aBase) { std::thread t([&] () { aBase.Run(); }); t.join(); }
Tags (comma-separated)
Save Edits
Cancel