Are C++11 thread_local variables automatically static?
According to the C++ Standard
When thread_local is applied to a variable of block scope the storage-class-specifier static is implied if it does not appear explicitly
So it means that this definition
void f() {
thread_local vector<int> V;
V.clear();
... // use V as a temporary variable
}
is equivalent to
void f() {
static thread_local vector<int> V;
V.clear();
... // use V as a temporary variable
}
However, a static variable is not the same as a thread_local variable.
1 All variables declared with the thread_local keyword have thread storage duration. The storage for these entities shall last for the duration of the thread in which they are created. There is a distinct object or reference per thread, and use of the declared name refers to the entity associated with the current thread
To distinguish these variables the standard introduces a new term thread storage duration along with static storage duration.
Yes, "thread-local storage" is very similar to "global" (or "static storage"), only that instead of "duration of the entire program" you have "duration of the entire thread". So a block-local thread-local variable is initialized the first time control passes through its declaration, but separately within each thread, and it's destroyed when the thread ends.
When used with thread_local
, static
is implied in block-scope (see @Vlad's answer), requied for a class member; I guess, means linkage for namespace scope.
Per 9.2/6:
Within a class definition, a member shall not be declared with the thread_local storage-class-specifier unless also declared static
To answer the original question:
Are C++11 thread_local variables automatically static?
There is no choice, except for namespace-scope variables.
Is there a difference between these two code segments:
No.