JDK-8249945 : Improve ARRAY_SIZE()
  • Type: Enhancement
  • Component: hotspot
  • Sub-Component: runtime
  • Affected Version: 16
  • Priority: P4
  • Status: Resolved
  • Resolution: Fixed
  • Submitted: 2020-07-23
  • Updated: 2020-08-12
  • Resolved: 2020-07-24
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 16
16 b08Fixed
Related Reports
Relates :  
Description
The ARRAY_SIZE() macro packages up an idiom for getting the compile-time constant number of elements in an array of some arbitrary element type.  However, it has the defect that later maintenance that changes the array expression to a pointer type will still quietly compile, but will produce entirely the wrong value, which can be unpleasant to debug.  There is a different implementation possible in C++ (the current approach is from C) that avoids that problem, producing a compile-time error in such a situation.  Specifically

{code:c++}
// array_size_impl is a function that takes a reference to T[N] and
// returns a reference to char[N].  It is not ODR-used, so not defined.
template<typename T, size_t N> char (&array_size_impl(T (&)[N]))[N];

#define ARRAY_SIZE(array) sizeof(array_size_impl(array))
{code}

Unfortunately, in C++03 this runs afoul of 14.3.1, which forbids local types as template parameters.  If the array element type is a local type, this implementation will fail to compile.  C++11 removed that restriction.

Note that C++17 adds (in <iterator>)

{code:c++}
template<typename T, size_t N>
constexpr size_t size(const T (&array)[N]) noexcept;
{code}

which returns N.  However, this doesn't work in constexpr contexts when the argument is a data member, because the implicit reference to {{this}} makes the call not constexpr.  So this is not really an eventual replacement for the above ARRAY_SIZE macro.

Comments
URL: https://hg.openjdk.java.net/jdk/jdk/rev/7f4d7d34b92d User: kbarrett Date: 2020-07-24 09:43:59 +0000
24-07-2020