gpt4 book ai didi

c++ - 可以替换 std::thread 对象吗?

转载 作者:太空宇宙 更新时间:2023-11-04 15:16:56 24 4
gpt4 key购买 nike

根据我在 C++ 在线文档中收集到的信息,分配给连接的 std::thread 对象应该调用其析构函数并代表合法操作。是这样吗?

这里有一些例子来说明我的意思:

#include <thread>
#include <vector>

using namespace std;

int main()
{
vector<thread> tvec;
for(int = 0; i < 3; ++i)
{
tvec.push_back(thread(foo));
}
for(size_t i = 0; i < 3; ++i)
{
tvec[i].join();
tvec[i] = thread(foo); // is this ok?
}
for(auto& t : tvec)
{
t.join();
}
}

最佳答案

assigning to a joined std::thread object should call its destructor

不应该!析构函数仅在对象被销毁时调用,因此得名。

and represents a legitimate operation

只要线程不可连接(如您的示例中的情况)就可以了。否则,将调用 terminate

如果您要阅读标准而不是可疑的在线“文档”,您会在 [thread.thread.assign] 中找到

Effects: If joinable(), calls terminate(). Otherwise, assigns the state of x to *this and sets x to a default constructed state.

关于c++ - 可以替换 std::thread 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30309174/

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