我有以下使用线程和静态变量初始化的 C++11 代码。我的问题是:
C++ 语言对静态变量的单一初始化有什么保证或保证——下面的代码显示了正确的值,但是我似乎在新标准中找不到提到内存模型应该如何与线程交互的段落。变量何时成为线程本地的?
#include <iostream>
#include <thread>
class theclass
{
public:
theclass(const int& n)
:n_(n)
{ printf("aclass(const int& n){}\n"); }
int n() const { return n_; }
private:
int n_;
};
int operator+(const theclass& c, int n)
{
return c.n() + n;
}
void foo()
{
static theclass x = 1;
static theclass y = x + 1;
printf("%d %d\n",x.n(),y.n());
}
int main()
{
std::thread t1(&foo);
std::thread t2(&foo);
t1.join();
t2.join();
return 0;
}