以下代码会出现栈溢出(stack overflow)
#include <stdio.h>
#include <thread>
#define MAX_SIZE 3145728
class A {
public:
A() :worker_(std::thread(&A::task, this)) {}
private:
void task() {
char buf[MAX_SIZE];
printf("running...");
while (1);
}
std::thread worker_;
};
int main() {
A a;
return 0;
}
原因是buf数组空间分配过大。
调试的时候会发现,连线程的第一步都不会执行,程序直接挂掉。
应当改成动态分配。