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