Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8329818

HotSpot Style Guide should explicitly permit the "union trick"

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P4 P4
    • tbd
    • None
    • hotspot

      The C++ Standard says that a union can only have one active member at at time, the member most recently written. Reading from an inactive member is undefined behavior. The only exception is the common initial subsequence rule.

      There are several places where HotSpot stores one member and reads from another, usually as a means to bitwise convert between types. This is the so-called "union trick" or "type-punning". While UB according to the C++ standard, all supported compilers support this as an extension. gcc and msvc have explicitly documented supporting it for a long time, and clang probably does too.

      See, for example,
      https://gcc.gnu.org/onlinedocs/gcc-13.2.0/gcc/Optimize-Options.html#Type-punning

      The Style Guide should explicit permit this usage.

      Note that in general, changing which union member is active in C++ requires explicit destruction and placement new construction, in order to ensure the prior value is properly destroyed and there is no attempt to destroy a non-existent value in the new member.

      Note also that C99 changed to permit this usage.

            Unassigned Unassigned
            kbarrett Kim Barrett
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: