gpt4 book ai didi

c++ - 为什么这个 cppreference 演示程序会导致段错误?

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

我正在审查 std::move 的变体通过在我的编译器上测试它的功能。由于某种原因,这个程序在最新的 clang++ 和 g++4.8 中都失败了。在我看来,这看起来像是一个正确的程序,应该可以工作。

g++-4.8 -std=c++1y -O3 -Wall -pthread main.cpp && ./a.out

terminate called without an active exception
/tmp/1370796977-600590525/cmd.sh: line 7: 22819 Aborted (core dumped) ./a.out

#include <iostream>
#include <vector>
#include <list>
#include <iterator>
#include <thread>
#include <chrono>

void f(int n)
{
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "thread " << n << " ended" << '\n';
}

int main()
{
std::vector<std::thread> v;
v.emplace_back(f, 1);
v.emplace_back(f, 2);
v.emplace_back(f, 3);
std::list<std::thread> l;

for(auto& t : l) t.join();
}

我注意到导致错误的部分是 emplace_back 行。当我删除它们时,程序会正常编译。为什么会发生这种情况,为什么它在我迄今为止尝试过的所有编译器上都失败了?

最佳答案

您没有加入 main() 中的线程。你需要

 for(auto& t : v) t.join();
// ^ Look, v not l

或者,将此行放在原始循环之前,将线程从 v 移动到 l:

std::move(v.begin(), v.end(), std::back_inserter(l)); 
for(auto& t : l) t.join();

关于c++ - 为什么这个 cppreference 演示程序会导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17012011/

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