1% HotSpot Coding Style
2
3## Introduction
4
5This is a collection of rules, guidelines, and suggestions for writing
6HotSpot code.  Following these will help new code fit in with existing
7HotSpot code, making it easier to read and maintain.  Failure to
8follow these guidelines may lead to discussion during code reviews, if
9not outright rejection of a change.
10
11### Why Care About Style?
12
13Some programmers seem to have lexers and even C preprocessors
14installed directly behind their eyeballs. The rest of us require code
15that is not only functionally correct but also easy to read. More than
16that, since there is no one style for easy-to-read code, and since a
17mashup of many styles is just as confusing as no style at all, it is
18important for coders to be conscious of the many implicit stylistic
19choices that historically have gone into the HotSpot code base.
20
21Some of these guidelines are driven by the cross-platform requirements
22for HotSpot.  Shared code must work on a variety of platforms, and may
23encounter deficiencies in some.  Using platform conditionalization in
24shared code is usually avoided, while shared code is strongly
25preferred to multiple platform-dependent implementations, so some
26language features may be recommended against.
27
28Some of the guidelines here are relatively arbitrary choices among
29equally plausible alternatives.  The purpose of stating and enforcing
30these rules is largely to provide a consistent look to the code.  That
31consistency makes the code more readable by avoiding non-functional
32distractions from the interesting functionality.
33
34When changing pre-existing code, it is reasonable to adjust it to
35match these conventions. Exception: If the pre-existing code clearly
36conforms locally to its own peculiar conventions, it is not worth
37reformatting the whole thing.  Also consider separating changes that
38make extensive stylistic updates from those which make functional
39changes.
40
41### Counterexamples and Updates
42
43Many of the guidelines mentioned here have (sometimes widespread)
44counterexamples in the HotSpot code base. Finding a counterexample is
45not sufficient justification for new code to follow the counterexample
46as a precedent, since readers of your code will rightfully expect your
47code to follow the greater bulk of precedents documented here.
48
49Occasionally a guideline mentioned here may be just out of synch with
50the actual HotSpot code base. If you find that a guideline is
51consistently contradicted by a large number of counterexamples, please
52bring it up for discussion and possible change. The architectural
53rule, of course, is "When in Rome do as the Romans". Sometimes in the
54suburbs of Rome the rules are a little different; these differences
55can be pointed out here.
56
57Proposed changes should be discussed on the
58[HotSpot Developers](mailto:hotspot-dev@openjdk.java.net) mailing
59list, and approved by
60[rough consensus](https://en.wikipedia.org/wiki/Rough_consensus) of
61the [HotSpot Group](https://openjdk.java.net/census#hotspot) Members.
62The Group Lead determines whether consensus has been reached.
63Changes are likely to be cautious and incremental, since HotSpot
64coders have been using these guidelines for years.
65
66## Structure and Formatting
67
68### Factoring and Class Design
69
70* Group related code together, so readers can concentrate on one
71section of one file.
72
73* Classes are the primary code structuring mechanism.  Place related
74functionality in a class, or a set of related classes.  Use of either
75namespaces or public non-member functions is rare in HotSpot code.
76Static non-member functions are not uncommon.
77
78* If a class `FooBar` is going to be used in more than one place, put it
79a file named fooBar.hpp and fooBar.cpp. If the class is a sidekick
80to a more important class `BazBat`, it can go in bazBat.hpp.
81
82* Put a member function `FooBar::bang` into the same file that defined
83`FooBar`, or its associated *.inline.hpp or *.cpp file.
84
85* Use public accessor functions for member variables accessed
86outside the class.
87
88* Assign names to constant literals and use the names instead.
89
90* Keep functions small, a screenful at most.  Split out chunks of
91logic into file-local classes or static functions if needed.
92
93* Factor away nonessential complexity into local inline helper
94functions and helper classes.
95
96* Think clearly about internal invariants that apply to each class,
97and document them in the form of asserts within member functions.
98
99* Make simple, self-evident contracts for member functions.  If you cannot
100communicate a simple contract, redesign the class.
101
102* Implement classes as if expecting rough usage by clients. Check for
103incorrect usage of a class using `assert(...)`, `guarantee(...)`,
104`ShouldNotReachHere()` and comments wherever needed.  Performance is
105almost never a reason to omit asserts.
106
107* When possible, design as if for reusability.  This forces a clear
108design of the class's externals, and clean hiding of its internals.
109
110* Initialize all variables and data structures to a known state. If a
111class has a constructor, initialize it there.
112
113* Do no optimization before its time. Prove the need to optimize.
114
115* When you must defactor to optimize, preserve as much structure as
116possible. If you must hand-inline some name, label the local copy with
117the original name.
118
119* If you need to use a hidden detail (e.g., a structure offset), name
120it (as a constant or function) in the class that owns it.
121
122* Don't use the Copy and Paste keys to replicate more than a couple
123lines of code.  Name what you must repeat.
124
125* If a class needs a member function to change a user-visible attribute, the
126change should be done with a "setter" accessor matched to the simple
127"getter".
128
129### Source Files
130
131* All source files must have a globally unique basename.  The build
132system depends on this uniqueness.
133
134* Do not put non-trivial function implementations in .hpp files. If
135the implementation depends on other .hpp files, put it in a .cpp or
136a .inline.hpp file.
137
138* .inline.hpp files should only be included in .cpp or .inline.hpp
139files.
140
141* All .cpp files include precompiled.hpp as the first include line.
142
143* precompiled.hpp is just a build time optimization, so don't rely on
144it to resolve include problems.
145
146* Keep the include lines alphabetically sorted.
147
148* Put conditional inclusions (`#if ...`) at the end of the include list.
149
150### JTReg Tests
151
152* JTReg tests should have meaningful names.
153
154* JTReg tests associated with specific bugs should be tagged with the
155`@bug` keyword in the test description.
156
157* JTReg tests should be organized by component or feature under
158`test/`, in a directory hierarchy that generally follows that of the
159`src/` directory. There may be additional subdirectories to further
160categorize tests by feature. This structure makes it easy to run a
161collection of tests associated with a specific feature by specifying
162the associated directory as the source of the tests to run.
163
164    * Some (older) tests use the associated bug number in the directory
165    name, the test name, or both.  That naming style should no longer be
166    used, with existing tests using that style being candidates for migration.
167
168### Naming
169
170* The length of a name may be correlated to the size of its scope.  In
171particular, short names (even single letter names) may be fine in a
172small scope, but are usually inappropriate for larger scopes.
173
174* Prefer whole words rather than abbreviations, unless the
175abbreviation is more widely used than the long form in the code's
176domain.
177
178* Choose names consistently. Do not introduce spurious
179variations. Abbreviate corresponding terms to a consistent length.
180
181* Global names must be unique, to avoid [One Definition Rule][ODR] (ODR)
182violations.  A common prefixing scheme for related global names is
183often used.  (This is instead of using namespaces, which are mostly
184avoided in HotSpot.)
185
186* Don't give two names to the semantically same thing.  But use
187different names for semantically different things, even if they are
188representationally the same.  (So use meaningful `typedef` or template
189alias names where appropriate.)
190
191* When choosing names, avoid categorical nouns like "variable",
192"field", "parameter", "value", and verbs like "compute", "get".
193(`storeValue(int param)` is bad.)
194
195* Type names and global names should use mixed-case with the first
196letter of each word capitalized (`FooBar`).
197
198* Embedded abbreviations in
199otherwise mixed-case names are usually capitalized entirely rather
200than being treated as a single word with only the initial letter
201capitalized, e.g. "HTML" rather than "Html".
202
203* Function and local variable names use lowercase with words separated
204by a single underscore (`foo_bar`).
205
206* Class data member names have a leading underscore, and use lowercase
207with words separated by a single underscore (`_foo_bar`).
208
209* Constant names may be upper-case or mixed-case, according to
210historical necessity.  (Note: There are many examples of constants
211with lowercase names.)
212
213* Constant names should follow an existing pattern, and must have a
214distinct appearance from other names in related APIs.
215
216* Class and type names should be noun phrases. Consider an "er" suffix
217for a class that represents an action.
218
219* Function names should be verb phrases that reflect changes of state
220known to a class's user, or else noun phrases if they cause no change
221of state visible to the class's user.
222
223* Getter accessor names are noun phrases, with no "`get_`" noise
224word. Boolean getters can also begin with "`is_`" or "`has_`".  Member
225function for reading data members usually have the same name as the
226data member, exclusive of the leading underscore.
227
228* Setter accessor names prepend "`set_`" to the getter name.
229
230* Other member function names are verb phrases, as if commands to the receiver.
231
232* Avoid leading underscores (as "`_oop`") except in cases required
233above. (Names with leading underscores can cause portability
234problems.)
235
236### Commenting
237
238* Clearly comment subtle fixes.
239
240* Clearly comment tricky classes and functions.
241
242* If you have to choose between commenting code and writing wiki
243content, comment the code. Link from the wiki to the source file if
244it makes sense.
245
246* As a general rule don't add bug numbers to comments (they would soon
247overwhelm the code). But if the bug report contains significant
248information that can't reasonably be added as a comment, then refer to
249the bug report.
250
251* Personal names are discouraged in the source code, which is a team
252product.
253
254### Macros
255
256* You can almost always use an inline function or class instead of a
257macro. Use a macro only when you really need it.
258
259* Templates may be preferable to multi-line macros. (There may be
260subtle performance effects with templates on some platforms; revert
261to macros if absolutely necessary.)
262
263* `#ifdef`s should not be used to introduce platform-specific code
264into shared code (except for `_LP64`). They must be used to manage
265header files, in the pattern found at the top of every source
266file. They should be used mainly for major build features, including
267`PRODUCT`, `ASSERT`, `_LP64`, `INCLUDE_SERIALGC`, `COMPILER1`, etc.
268
269* For build features such as `PRODUCT`, use `#ifdef PRODUCT` for
270multiple-line inclusions or exclusions.
271
272* For short inclusions or exclusions based on build features, use
273macros like `PRODUCT_ONLY` and `NOT_PRODUCT`. But avoid using them
274with multiple-line arguments, since debuggers do not handle that
275well.
276
277* Use `CATCH`, `THROW`, etc. for HotSpot-specific exception processing.
278
279### Whitespace
280
281* In general, don't change whitespace unless it improves readability
282or consistency.  Gratuitous whitespace changes will make integrations
283and backports more difficult.
284
285* Use One-True-Brace-Style. The opening brace for a function or class
286is normally at the end of the line; it is sometimes moved to the
287beginning of the next line for emphasis.  Substatements are enclosed
288in braces, even if there is only a single statement.  Extremely simple
289one-line statements may drop braces around a substatement.
290
291* Indentation levels are two columns.
292
293* There is no hard line length limit.  That said, bear in mind that
294excessively long lines can cause difficulties.  Some people like to
295have multiple side-by-side windows in their editors, and long lines
296may force them to choose among unpleasant options. They can use wide
297windows, reducing the number that can fit across the screen, and
298wasting a lot of screen real estate because most lines are not that
299long.  Alternatively, they can have more windows across the screen,
300with long lines wrapping (or worse, requiring scrolling to see in
301their entirety), which is harder to read.  Similar issues exist for
302side-by-side code reviews.
303
304* Tabs are not allowed in code. Set your editor accordingly.<br>
305(Emacs: `(setq-default indent-tabs-mode nil)`.)
306
307* Use good taste to break lines and align corresponding tokens on
308adjacent lines.
309
310* Use spaces around operators, especially comparisons and
311assignments. (Relaxable for boolean expressions and high-precedence
312operators in classic math-style formulas.)
313
314* Put spaces on both sides of control flow keywords `if`, `else`,
315`for`, `switch`, etc.  Don't add spaces around the associated
316_control_ expressions.  Examples:
317
318    ```
319    while (test_foo(args...)) {   // Yes
320    while(test_foo(args...)) {    // No, missing space after while
321    while ( test_foo(args...) ) { // No, excess spaces around control
322    ```
323
324* Use extra parentheses in expressions whenever operator precedence
325seems doubtful. Always use parentheses in shift/mask expressions
326(`<<`, `&`, `|`).  Don't add whitespace immediately inside
327parentheses.
328
329* Use more spaces and blank lines between larger constructs, such as
330classes or function definitions.
331
332* If the surrounding code has any sort of vertical organization,
333adjust new lines horizontally to be consistent with that
334organization. (E.g., trailing backslashes on long macro definitions
335often align.)
336
337### Miscellaneous
338
339* Use the [Resource Acquisition Is Initialization][RAII] (RAII)
340design pattern to manage bracketed critical
341sections. See class `ResourceMark` for an example.
342
343* Avoid implicit conversions to `bool`.
344    * Use `bool` for boolean values.
345    * Do not use ints or pointers as (implicit) booleans with `&&`, `||`,
346      `if`, `while`. Instead, compare explicitly, i.e. `if (x != 0)` or
347      `if (ptr != nullptr)`, etc.
348    * Do not use declarations in _condition_ forms, i.e. don't use
349      `if (T v = value) { ... }`.
350
351* Use functions from globalDefinitions.hpp and related files when
352performing bitwise
353operations on integers. Do not code directly as C operators, unless
354they are extremely simple. (Examples: `align_up`, `is_power_of_2`,
355`exact_log2`.)
356
357* Use arrays with abstractions supporting range checks.
358
359* Always enumerate all cases in a switch statement or provide a default
360case. It is ok to have an empty default with comment.
361
362
363## Use of C++ Features
364
365HotSpot was originally written in a subset of the C++98/03 language.
366More recently, support for C++14 is provided, though again,
367HotSpot only uses a subset.  (Backports to JDK versions lacking
368support for more recent Standards must of course stick with the
369original C++98/03 subset.)
370
371This section describes that subset.  Features from the C++98/03
372language may be used unless explicitly excluded here.  Features from
373C++11 and C++14 may be explicitly permitted or explicitly excluded,
374and discussed accordingly here.  There is a third category, undecided
375features, about which HotSpot developers have not yet reached a
376consensus, or perhaps have not discussed at all.  Use of these
377features is also excluded.
378
379(The use of some features may not be immediately obvious and may slip
380in anyway, since the compiler will accept them.  The code review
381process is the main defense against this.)
382
383Some features are discussed in their own subsection, typically to provide
384more extensive discussion or rationale for limitations.  Features that
385don't have their own subsection are listed in omnibus feature sections
386for permitted, excluded, and undecided features.
387
388Lists of new features for C++11 and C++14, along with links to their
389descriptions, can be found in the online documentation for some of the
390compilers and libraries.  The C++14 Standard is the definitive
391description.
392
393* [C++ Standards Support in GCC](https://gcc.gnu.org/projects/cxx-status.html)
394* [C++ Support in Clang](https://clang.llvm.org/cxx_status.html)
395* [Visual C++ Language Conformance](https://docs.microsoft.com/en-us/cpp/visual-cpp-language-conformance)
396* [libstdc++ Status](https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html)
397* [libc++ Status](https://libcxx.llvm.org/cxx1y_status.html)
398
399As a rule of thumb, permitting features which simplify writing code
400and, especially, reading code, is encouraged.
401
402Similar discussions for some other projects:
403
404* [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) &mdash;
405Currently (2020) targeting C++17.
406
407* [C++11 and C++14 use in Chromium](https://chromium-cpp.appspot.com) &mdash;
408Categorizes features as allowed, banned, or to be discussed.
409
410* [llvm Coding Standards](https://llvm.org/docs/CodingStandards.html) &mdash;
411Currently (2020) targeting C++14.
412
413* [Using C++ in Mozilla code](https://firefox-source-docs.mozilla.org/code-quality/coding-style/using_cxx_in_firefox_code.html) &mdash;
414C++17 support is required for recent versions (2020).
415
416### Error Handling
417
418Do not use exceptions. Exceptions are disabled by the build configuration
419for some platforms.
420
421Rationale: There is significant concern over the performance cost of
422exceptions and their usage model and implications for maintainable code.
423That's not just a matter of history that has been fixed; there remain
424questions and problems even today (2019). See, for example, [Zero cost
425deterministic
426exceptions](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r0.pdf).
427Because of this, HotSpot has always used a build configuration that disables
428exceptions where that is available. As a result, HotSpot code uses error
429handling mechanisms such as two-phase construction, factory functions,
430returning error codes, and immediate termination. Even if the cost of
431exceptions were not a concern, the existing body of code was not written with
432exception safety in mind. Making HotSpot exception safe would be a very large
433undertaking.
434
435In addition to the usual alternatives to exceptions, HotSpot provides its
436own exception mechanism. This is based on a set of macros defined in
437utilities/exceptions.hpp.
438
439### RTTI (Runtime Type Information)
440
441Do not use [Runtime Type Information][RTTI] (RTTI).
442[RTTI][] is disabled by the build configuration for some
443platforms.  Among other things, this means `dynamic_cast` cannot be used.
444
445Rationale: Other than to implement exceptions (which HotSpot doesn't use),
446most potential uses of [RTTI][] are better done via virtual functions.  Some of
447the remainder can be replaced by bespoke mechanisms.  The cost of the
448additional runtime data structures needed to support [RTTI][] are deemed not
449worthwhile, given the alternatives.
450
451### Memory Allocation
452
453Do not use the standard global allocation and deallocation functions
454(operator new and related functions).  Use of these functions by HotSpot
455code is disabled for some platforms.
456
457Rationale: HotSpot often uses "resource" or "arena" allocation.  Even
458where heap allocation is used, the standard global functions are
459avoided in favor of wrappers around malloc and free that support the
460VM's Native Memory Tracking (NMT) feature.
461
462Native memory allocation failures are often treated as non-recoverable.
463The place where "out of memory" is (first) detected may be an innocent
464bystander, unrelated to the actual culprit.
465
466### Class Inheritance
467
468Use public single inheritance.
469
470Prefer composition rather than non-public inheritance.
471
472Restrict inheritance to the "is-a" case; use composition rather than
473non-is-a related inheritance.
474
475Avoid multiple inheritance.  Never use virtual inheritance.
476
477### Namespaces
478
479Avoid using namespaces.  HotSpot code normally uses "all static"
480classes rather than namespaces for grouping.  An "all static" class is
481not instantiable, has only static members, and is normally derived
482(possibly indirectly) from the helper class `AllStatic`.
483
484Benefits of using such classes include:
485
486* Provides access control for members, which is unavailable with
487namespaces.
488
489* Avoids [Argument Dependent Lookup][ADL] (ADL).
490
491* Closed for additional members.  Namespaces allow names to be added in
492multiple contexts, making it harder to see the complete API.
493
494Namespaces should be used only in cases where one of those "benefits"
495is actually a hindrance.
496
497In particular, don't use anonymous namespaces.  They seem like they should
498be useful, and indeed have some real benefits for naming and generated code
499size on some platforms.  Unfortunately, debuggers don't seem to like them at
500all.
501
502<https://groups.google.com/forum/#!topic/mozilla.dev.platform/KsaG3lEEaRM><br>
503Suggests Visual Studio debugger might not be able to refer to
504anonymous namespace symbols, so can't set breakpoints in them.
505Though the discussion seems to go back and forth on that.
506
507<https://firefox-source-docs.mozilla.org/code-quality/coding-style/coding_style_cpp.html><br>
508Search for "Anonymous namespaces"
509Suggests preferring "static" to anonymous namespaces where applicable,
510because of poor debugger support for anonymous namespaces.
511
512<https://sourceware.org/bugzilla/show_bug.cgi?id=16874><br>
513Bug for similar gdb problems.
514
515### C++ Standard Library
516
517Avoid using the C++ Standard Library.
518
519Historically, HotSpot has mostly avoided use of the Standard
520Library.
521
522(It used to be impossible to use most of it in shared code,
523because the build configuration for Solaris with Solaris Studio made
524all but a couple of pieces inaccessible.  Support for header-only
525parts was added in mid-2017.  Support for Solaris was removed
526in 2020.)
527
528Some reasons for this include
529
530* Exceptions. Perhaps the largest core issue with adopting the use of
531Standard Library facilities is exceptions. HotSpot does not use
532exceptions and, for platforms which allow doing so, builds with them
533turned off.  Many Standard Library facilities implicitly or explicitly
534use exceptions.
535
536* `assert`.  An issue that is quickly encountered is the `assert` macro name
537collision ([JDK-8007770](https://bugs.openjdk.java.net/browse/JDK-8007770)).
538Some mechanism for addressing this would be needed before much of the
539Standard Library could be used.  (Not all Standard Library implementations
540use assert in header files, but some do.)
541
542* Memory allocation. HotSpot requires explicit control over where
543allocations occur. The C++98/03 `std::allocator` class is too limited
544to support our usage.  (Changes in more recent Standards may remove
545this limitation.)
546
547* Implementation vagaries. Bugs, or simply different implementation choices,
548can lead to different behaviors among the various Standard Libraries we need
549to deal with.
550
551* Inconsistent naming conventions. HotSpot and the C++ Standard use
552different naming conventions. The coexistence of those different conventions
553might appear jarring and reduce readability.
554
555There are a few exceptions to this rule.
556
557* `#include <new>` to use placement `new`, `std::nothrow`, and `std::nothrow_t`.
558* `#include <limits>` to use `std::numeric_limits`.
559* `#include <type_traits>`.
560* `#include <cstddef>` to use `std::nullptr_t`.
561
562TODO: Rather than directly \#including (permitted) Standard Library
563headers, use a convention of \#including wrapper headers (in some
564location like hotspot/shared/stdcpp).  This provides a single place
565for dealing with issues we might have for any given header, esp.
566platform-specific issues.
567
568### Type Deduction
569
570Use type deduction only if it makes the code clearer or safer.  Do not
571use it merely to avoid the inconvenience of writing an explicit type,
572unless that type is itself difficult to write.  An example of the
573latter is a function template return type that depends on template
574parameters in a non-trivial way.
575
576There are several contexts where types are deduced.
577
578* Function argument deduction.  This is always permitted, and indeed
579encouraged.  It is nearly always better to allow the type of a
580function template argument to be deduced rather than explicitly
581specified.
582
583* `auto` variable declarations
584([n1984](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1984.pdf))<br>
585For local variables, this can be used to make the code clearer by
586eliminating type information that is obvious or irrelevant.  Excessive
587use can make code much harder to understand.
588
589* Function return type deduction
590([n3638](https://isocpp.org/files/papers/N3638.html))<br>
591Only use if the function body has a very small number of `return`
592statements, and generally relatively little other code.
593
594* Generic lambdas.  Lambdas are not (yet) permitted.
595
596* Lambda init captures.  Lambdas are not (yet) permitted.
597
598### Expression SFINAE
599
600[Substitution Failure Is Not An Error][SFINAE] (SFINAE)
601is a template metaprogramming technique that makes use of
602template parameter substitution failures to make compile-time decisions.
603
604C++11 relaxed the rules for what constitutes a hard-error when
605attempting to substitute template parameters with template arguments,
606making most deduction errors be substitution errors; see
607([n2634](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2634.html)).
608This makes [SFINAE][] more powerful and easier to use.  However, the
609implementation complexity for this change is significant, and this
610seems to be a place where obscure corner-case bugs in various
611compilers can be found.  So while this feature can (and indeed should)
612be used (and would be difficult to avoid), caution should be used when
613pushing to extremes.
614
615Here are a few closely related example bugs:<br>
616<https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95468><br>
617<https://developercommunity.visualstudio.com/content/problem/396562/sizeof-deduced-type-is-sometimes-not-a-constant-ex.html>
618
619### enum
620
621Where appropriate, _scoped-enums_ should be used.
622([n2347](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2347.pdf))
623
624Use of _unscoped-enums_ is permitted, though ordinary constants may be
625preferable when the automatic initializer feature isn't used.
626
627The underlying type (the _enum-base_) of an unscoped enum type should
628always be specified explicitly.  When unspecified, the underlying type
629is dependent on the range of the enumerator values and the platform.
630
631The underlying type of a _scoped-enum_ should also be specified
632explicitly if conversions may be applied to values of that type.
633
634Due to bugs in certain (very old) compilers, there is widespread use
635of enums and avoidance of in-class initialization of static integral
636constant members.  Compilers having such bugs are no longer supported.
637Except where an enum is semantically appropriate, new code should use
638integral constants.
639
640### thread_local
641
642Do not use `thread_local`
643([n2659](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2659.htm));
644instead, use the HotSpot macro `THREAD_LOCAL`.  The initializer must
645be a constant expression.
646
647As was discussed in the review for
648[JDK-8230877](https://mail.openjdk.java.net/pipermail/hotspot-dev/2019-September/039487.html),
649`thread_local` allows dynamic initialization and destruction
650semantics.  However, that support requires a run-time penalty for
651references to non-function-local `thread_local` variables defined in a
652different translation unit, even if they don't need dynamic
653initialization.  Dynamic initialization and destruction of
654namespace-scoped thread local variables also has the same ordering
655problems as for ordinary namespace-scoped variables.
656
657### nullptr
658
659Prefer `nullptr`
660([n2431](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2431.pdf))
661to `NULL`.  Don't use (constexpr or literal) 0 for pointers.
662
663For historical reasons there are widespread uses of both `NULL` and of
664integer 0 as a pointer value.
665
666### &lt;atomic&gt;
667
668Do not use facilities provided by the `<atomic>` header
669([n2427](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2427.html)),
670([n2752](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2752.htm));
671instead, use the HotSpot `Atomic` class and related facilities.
672
673Atomic operations in HotSpot code must have semantics which are
674consistent with those provided by the JDK's compilers for Java.  There
675are platform-specific implementation choices that a C++ compiler might
676make or change that are outside the scope of the C++ Standard, and
677might differ from what the Java compilers implement.
678
679In addition, HotSpot `Atomic` has a concept of "conservative" memory
680ordering, which may differ from (may be stronger than) sequentially
681consistent.  There are algorithms in HotSpot that are believed to rely
682on that ordering.
683
684### Uniform Initialization
685
686The use of _uniform initialization_
687([n2672](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2672.htm)),
688also known as _brace initialization_, is permitted.
689
690Some relevant sections from cppreference.com:
691
692* [initialization](https://en.cppreference.com/w/cpp/language/initialization)
693* [value initialization](https://en.cppreference.com/w/cpp/language/value_initialization)
694* [direct initialization](https://en.cppreference.com/w/cpp/language/direct_initialization)
695* [list initialization](https://en.cppreference.com/w/cpp/language/list_initialization)
696* [aggregate initialization](https://en.cppreference.com/w/cpp/language/aggregate_initialization)
697
698Although related, the use of `std::initializer_list` remains forbidden, as
699part of the avoidance of the C++ Standard Library in HotSpot code.
700
701### Additional Permitted Features
702
703* `constexpr`
704([n2235](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2235.pdf))
705([n3652](https://isocpp.org/files/papers/N3652.html))
706
707* Sized deallocation
708([n3778](https://isocpp.org/files/papers/n3778.html))
709
710* Variadic templates
711([n2242](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2242.pdf))
712([n2555](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2555.pdf))
713
714* Static assertions
715([n1720](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1720.html))
716
717* `decltype`
718([n2343](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2343.pdf))
719([n3276](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3276.pdf))
720
721* Right angle brackets
722([n1757](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1757.html))
723
724* Default template arguments for function templates
725([CWG D226](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#226))
726
727* Template aliases
728([n2258](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2258.pdf))
729
730* Delegating constructors
731([n1986](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1986.pdf))
732
733* Explicit conversion operators
734([n2437](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2437.pdf))
735
736* Standard Layout Types
737([n2342](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2342.htm))
738
739* Defaulted and deleted functions
740([n2346](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2346.htm))
741
742* Dynamic initialization and destruction with concurrency
743([n2660](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm))
744
745* `final` virtual specifiers for classes and virtual functions
746([n2928](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2009/n2928.htm)),
747([n3206](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3206.htm)),
748([n3272](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3272.htm))
749
750* Local and unnamed types as template parameters
751([n2657](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2657.htm))
752
753* Range-based `for` loops
754([n2930](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2009/n2930.html))
755([range-for](https://en.cppreference.com/w/cpp/language/range-for))
756
757### Excluded Features
758
759* New string and character literals
760    * New character types
761    ([n2249](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2249.html))
762    * Unicode string literals
763    ([n2442](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2442.htm))
764    * Raw string literals
765    ([n2442](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2442.htm))
766    * Universal character name literals
767    ([n2170](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2170.html))
768
769    HotSpot doesn't need any of the new character and string literal
770    types.
771
772* User-defined literals
773([n2765](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2765.pdf)) &mdash;
774User-defined literals should not be added casually, but only
775through a proposal to add a specific UDL.
776
777* Inline namespaces
778([n2535](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2535.htm)) &mdash;
779HotSpot makes very limited use of namespaces.
780
781* `using namespace` directives.  In particular, don't use `using
782namespace std;` to avoid needing to qualify Standard Library names.
783
784* Propagating exceptions
785([n2179](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2179.html)) &mdash;
786HotSpot does not permit the use of exceptions, so this feature isn't useful.
787
788* Avoid namespace-scoped variables with non-constexpr initialization.
789In particular, avoid variables with types requiring non-trivial
790initialization or destruction.  Initialization order problems can be
791difficult to deal with and lead to surprises, as can destruction
792ordering.  HotSpot doesn't generally try to cleanup on exit, and
793running destructors at exit can also lead to problems.
794
795* `[[deprecated]]` attribute
796([n3760](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3760.html)) &mdash;
797Not relevant in HotSpot code.
798
799* Avoid most operator overloading, preferring named functions.  When
800operator overloading is used, ensure the semantics conform to the
801normal expected behavior of the operation.
802
803* Avoid most implicit conversion constructors and (implicit or explicit)
804conversion operators.  (Note that conversion to `bool` isn't needed
805in HotSpot code because of the "no implicit boolean" guideline.)
806
807* Avoid covariant return types.
808
809* Avoid `goto` statements.
810
811### Undecided Features
812
813This list is incomplete; it serves to explicitly call out some
814features that have not yet been discussed.
815
816* `overrides` virtual specifiers for virtual functions
817([n3272](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3272.htm))
818
819* Trailing return type syntax for functions
820([n2541](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2541.htm))
821
822* Variable templates
823([n3651](https://isocpp.org/files/papers/N3651.pdf))
824
825* Member initializers and aggregates
826([n3653](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3653.html))
827
828* `[[noreturn]]` attribute
829([n2761](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2761.pdf))
830
831* Rvalue references and move semantics
832
833* Lambdas
834
835
836[ADL]: https://en.cppreference.com/w/cpp/language/adl
837  "Argument Dependent Lookup"
838
839[ODR]: https://en.cppreference.com/w/cpp/language/definition
840  "One Definition Rule"
841
842[RAII]: https://en.cppreference.com/w/cpp/language/raii
843  "Resource Acquisition Is Initialization"
844
845[RTTI]: https://en.wikipedia.org/wiki/Run-time_type_information
846  "Runtime Type Information"
847
848[SFINAE]: https://en.cppreference.com/w/cpp/language/sfinae
849  "Substitution Failure Is Not An Error"
850