[英]Is it safe to pass const reference to temporary/annonymous lambda into std::thread constructor?
[英]Is it safe to pass arguments by reference into a std::thread function?
#include <thread>
#include <string>
#include <vector>
#include <chrono>
using namespace std;
void f(const vector<string>& coll)
{
this_thread::sleep_for(1h);
//
// Is coll guaranteed to be valid before exiting this function?
//
}
int main()
{
{
vector<string> coll(1024 * 1024 * 100);
thread(f, coll).detach();
}
//
// I know std::thread will copy arguments into itself by default,
// but I don't know whether these copied objects are still valid
// after the std::thread object has been destroyed.
//
while (true);
}
通過引用將參數傳遞給std :: thread函數是否安全?
作為@ TC的評論,你沒有傳遞對線程的引用,你只需在線程中復制一個向量:
thread(f, coll).detach(); // It's NOT pass by reference, but makes a copy.
如果你真的想通過引用傳遞,你應該這樣寫:
thread(f, std::ref(coll)).detach(); // Use std::ref to pass by reference
然后,如果線程試圖訪問向量,代碼將獲得段錯誤,因為當線程運行時,很可能向量已經被破壞(因為它超出了它在主程序中的范圍)。
所以對你的問題:
通過引用將參數傳遞給
std::thread
函數是否安全?
在退出此功能之前, coll
是否保證有效?
coll
到的構造函數std::thread
的main
功能,是因為coll
是一個對象,它是decay
復制。 這個decay
副本基本上move
了向量(因此它變為rvalue),它將在執行線程期間綁定到f
中的coll
參數。 (感謝@Praetorian的評論) 通過引用將參數傳遞給std::thread
函數是否安全?
decay
復制,所以你卻從未通過引用傳遞任何東西std::thread
。 參考std::decay
: http : //www.cplusplus.com/reference/type_traits/decay/
std::thread
的參數會發生什么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.