gpt4 book ai didi

c++ - 无法理解 std::thread 用法

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:06:04 29 4
gpt4 key购买 nike

我正在阅读有关 c++11 多线程的文档,并遇到了 std::thread 的这个例子。

代码:

void thread_task(int n) {
...
}

int main(int argc, const char *argv[])
{
std::thread threads[5];
for (int i = 0; i < 5; i++) {
threads[i] = std::thread(thread_task, i + 1);
}

return 0;
}

我不明白 threads[i] = std::thread(thread_task, i + 1);std::thread 是静态函数调用,并返回 std::thread 对象的引用吗?听起来不可思议,但似乎就是代码所说的那样。

因为我会这样写:

std::thread *threads[5];
for (int i = 0; i < 5; i++) {
threads[i] = new std::thread(thread_task, i + 1);
}

谢谢。

最佳答案

让我们来看看到底发生了什么:

std::thread threads[5];

这将创建一个包含 5 个 std::thread 对象的数组,这些对象是默认构造的。目前它们代表“不是线程”,因为这是状态默认构造让它们留在其中。

for (int i = 0; i < 5; i++) {
threads[i] = std::thread(thread_task, i + 1);
}

这使用了 operator= 的移动形式。因为线程不可复制,只能移动,thread& operator=(thread&& t) 被定义,而 thread& operator=(const thread& t) 不是。这会将 threads[i] 中的线程对象分配给新构造的 std::thread(thread_task, i + 1);

没有理由在这里使用指针数组。它只会增加内存泄漏的可能性。

关于c++ - 无法理解 std::thread 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18673073/

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