2016-11-20 220 views
1

這段代碼如何可能不工作? 我希望MyThread :: run可以使用任何類型的參數,參數是通過引用而不是按值傳遞的。C++ 11 std :: async不能通過引用使用可變參數模板參數

http://ideone.com/DUJu5M

#include <iostream> 
#include <future> 
#include <string> 

class MyThread { 

     std::future<void> future; 

    public: 

     template<class... Args> 
     MyThread(Args&&... myArgs) : 
     future(std::async(std::launch::async, &MyThread::run<Args&&...>, this, std::forward<Args>(myArgs)...)) 
     {} 

     template<class... Args> 
     void run(Args&&... myArgs) {} 
}; 

int main() { 
    std::string x; 
    MyThread thread(x); // Not working 
    MyThread thread(10); // Working 
    return 0; 
} 

回答

2

您可以使用std::ref傳遞一個reference_wrapper。標準庫功能將自動解壓縮,如std::bind/std::threadstd::async

int main() { 
    std::string x; 
    MyThread thread(std::ref(x)); // Not working 
    MyThread thread2(10); // Working 
    return 0; 
} 

demo

+0

哦,非常感謝你。我不認爲這是因爲std :: async使用容器來存儲參數,並且容器不能包含引用。 你覺得如果我在MyThread中將「std :: forward (myArgs)」改爲「std :: ref(std :: forward (myArgs))」以使其通用? 謝謝 – infiniteLoop

+0

@ user3782790只有在實際需要時纔會通過引用傳遞。當你處理多線程代碼時,很容易被懸掛的引用咬住。 – krzaq

+0

好點,謝謝 – infiniteLoop