C++ 11 std :: async不能通过引用使用可变参数模板参数

问题描述:

这段代码如何可能不工作? 我希望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; 
} 

您可以使用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