![](/img/trans.png)
[英]Is it safe to pass a lambda function that goes out of scope to a std::thread
[英]Is it safe if detached std::thread uses object that went out of scope?
想象一下,我啟動了一個std::thread
,它運行一個對象的成員函數。 如果該對象在我創建線程的main函數中超出范圍會發生什么?
class ThreadClass {
public:
ThreadClass(int i) : _a(i) {
}
void foo() {
sleep(10);
std::cout << "Is it safe here? " << _a << std::endl;
}
int _a;
};
int main() {
{
ThreadClass obj(3);
std::thread t(&ThreadClass::foo, &obj);
t.detach();
}
// Here obj goes out of scope
// What about thread?
sleep(20);
return 0;
}
這是一個未定義的行為嗎?
不,那段代碼不安全。 該thread
擁有對象的非擁有引用(通過指針&obj
的副本)。 一旦對象超出范圍,那就是懸空參考。
是的,它是未定義的行為。 更具體地說,您將最終遇到分段錯誤,因為該線程正在嘗試訪問不再存在的某個對象。 所以這就是我的建議:
obj
不會超出范圍的obj
(可能是全局的)。 new
創建一個對象,並使用std::shared_ptr
將指針傳遞給線程。 (在這種情況下,您必須確保線程調用delete
操作,以避免內存泄漏)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.