C++ 11 std :: async不能通过引用使用可变参数模板参数
问题描述:
这段代码如何可能不工作? 我希望MyThread :: run可以使用任何类型的参数,参数是通过引用而不是按值传递的。C++ 11 std :: async不能通过引用使用可变参数模板参数
#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 :: async使用容器来存储参数,并且容器不能包含引用。 你觉得如果我在MyThread中将“std :: forward(myArgs)”改为“std :: ref(std :: forward (myArgs))”以使其通用? 谢谢 –
infiniteLoop
@ user3782790只有在实际需要时才会通过引用传递。当你处理多线程代码时,很容易被悬挂的引用咬住。 – krzaq
好点,谢谢 – infiniteLoop