gpt4 book ai didi

c++ - 如果分离的 std::thread 使用超出范围的对象是否安全?

转载 作者:太空狗 更新时间:2023-10-29 20:02:57 28 4
gpt4 key购买 nike

假设我启动了一个 std::thread,它运行一个对象的成员函数。如果该对象超出我创建线程的主函数的范围,会发生什么情况?

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 的拷贝)。一旦对象超出范围,那就是悬空引用。

关于c++ - 如果分离的 std::thread 使用超出范围的对象是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33276873/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com