簡體   English   中英

將C ++ 11線程與純虛擬線程功能一起使用

[英]Using C++11 thread with pure virtual thread function

我有代碼,打算在單獨的線程中執行的對象從帶有純虛擬Run函數的基類派生。 我無法獲得以下(簡化的測試代碼)來運行新線程。

#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);
}

該代碼可以很好地編譯(這是成功的一半),但是“ Hello”從未輸出。 如果我做錯了什么,那我期望在某個時候出現運行時錯誤。 我正在使用gcc。

編輯:上面的代碼無法在VS2012上編譯,出現: error C2064: term does not evaluate to a function taking 0 arguments

您需要使用lambda而不是std::ref ,即

void ThreadTest(Base& aBase)
{
    std::thread t([&] ()
    {
        aBase.Run();
    });
    t.join();
}

您需要將-pthread添加到g ++命令行,如對此類似問題的答案中所述: https : //stackoverflow.com/a/6485728/39622

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM