1
這段代碼如何可能不工作? 我希望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