Skip to content

Commit 30b281d

Browse files
[stmt.dcl] add example of static/thread_local block variable initialization
Update source/statements.tex Co-authored-by: A. Jiang <de34@live.cn>
1 parent 1c22d62 commit 30b281d

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

source/statements.tex

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1038,11 +1038,30 @@
10381038
the first time control passes through its declaration; such a variable is
10391039
considered initialized upon the completion of its initialization. If the
10401040
initialization exits by throwing an exception, the initialization is not
1041-
complete, so it will be tried again the next time control enters the
1041+
complete, so it will be tried again the next time control passes through the
10421042
declaration.
1043-
If control enters the declaration concurrently while the variable is
1044-
being initialized, the concurrent execution shall wait for completion
1043+
If control passes through the declaration concurrently while the variable is
1044+
being initialized, the concurrent execution waits for completion
10451045
of the initialization.
1046+
\begin{example}
1047+
\begin{codeblock}
1048+
void f() {
1049+
static int x = 2; // OK
1050+
static std::string s = "hello"; // OK; if an exception is thrown during the
1051+
// initialization of \tcode{s}, \tcode{s} remains uninitialized, and
1052+
// an attempt to initialize \tcode{s} (but not \tcode{x}) will be
1053+
// made the next time \tcode{f} is called.
1054+
thread_local const char* w = "world"; // OK, initializes \tcode{w} to \tcode{"world"} on the main thread.
1055+
std::jthread([] {
1056+
thread_local int k = 4;
1057+
std::cout << k + x; // OK, prints \tcode{"6"}.
1058+
std::cout << s << ' '; // OK, prints \tcode{"hello "}.
1059+
std::cout << w; // Undefined behavior if \tcode{w} hasn't been constant initialized\iref{basic.start.static}.
1060+
// On this thread, control hasn't yet passed through
1061+
}); // the declaration of \tcode{w}.
1062+
}
1063+
\end{codeblock}
1064+
\end{example}
10461065
\begin{note}
10471066
A conforming implementation cannot introduce
10481067
any deadlock around execution of the initializer.

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy