为什么以下代码给我一个分段错误:
#include<iostream>
#include<thread>
#include<vector>
using namespace std;
double f(double a, double b, double* c) {
*c = a + b;
}
int main() {
vector<double> a ={1,2,3,4,5,6,7,8};
vector<double> b ={2,1,3,4,5,2,8,2};
int size = a.size();
vector<double> c(size);
vector<thread*> threads(size);
for (int i = 0; i < size; ++i) {
thread* t = new thread(f, a[i], b[i], &c[i]);
threads.push_back(t);
}
for (vector<thread*>::iterator it = threads.begin(); it != threads.end(); it++) {
(*it)->join();
}
cout << "Vector c is: ";
for (int i =0; i < size; ++i) {
cout << c[i] << " ";
}
}
我知道分段错误发生在使用迭代器的for循环内,但是我不确定为什么。
最佳答案
vector<thread*> threads(size);
声明创建一个带有
size
数量的默认初始化thread*
对象的 vector ,这些对象是nullptr
。然后,使用
push_back
插入其他非空对象,但空对象保留在那里,并在最后遍历vector时取消引用它们。