5
스레드 및 정적 변수 초기화를 사용하는 다음 C++ 11 코드가 있습니다. 내 질문 :C++ 정적 변수 초기화 및 스레드
C++ 언어가 정적 변수의 단일 초기화에 대한 보증 또는 보장은 무엇입니까? 아래 코드는 올바른 값을 표시하지만 새로운 표준에서 그 방법을 설명하는 구절을 찾을 수없는 것 같습니다. 메모리 모델은 스레드와 상호 작용해야합니다. 언제 변수가 thread-local이 되는가?
#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;
}