RFR: 8377895: Create sizeof_auto, to reduce narrowing conversions [v2]

Kim Barrett kbarrett at openjdk.org
Tue Feb 17 13:36:19 UTC 2026


On Mon, 16 Feb 2026 13:42:53 GMT, Leo Korinth <lkorinth at openjdk.org> wrote:

>> `sizeof_auto` is created so that we can reduce the amount of casting and thus make the code more type safe. The normal `sizeof` will return a `size_t` although the size of most stuff can be represented in a `uint8_t`. `sizeof_auto` will return the size in an as small unsigned type as is possible. The result is that expressions that uses `sizeof_auto` can convert to most integral types, and no explicit narrowing cast will be needed.
>> 
>> The change in `cpCache.hpp` is an example where we would get an implicit narrowing warning (if we had those enabled) using normal `sizeof`, but where `sizeof_auto` will not make the expression a `size_t` .
>
> Leo Korinth has updated the pull request incrementally with one additional commit since the last revision:
> 
>   Fix test for platforms that can not handle unsigned max sizes

Changes requested by kbarrett (Reviewer).

src/hotspot/share/utilities/globalDefinitions.hpp line 171:

> 169: #endif  // _LP64
> 170: 
> 171: // Use this instead of sizeof() if you want your expression not to be of type size_t

Needs a better description, about what it actually does.

src/hotspot/share/utilities/globalDefinitions.hpp line 186:

> 184: // Use this instead of sizeof() if you want your expression not to be of type size_t
> 185: template <typename T>
> 186: constexpr auto sizeof_auto(const T& t) {

I think this should be a macro, so it can avoid evaluating the argument, a la `sizeof`.
Expansion would use `decltype` of the argument.
This would either require different naming from the no-arg case, or doing macro overloading
on the number of arguments.  (I kind of remember tricks for doing that, but it's "hard" to
distinguish zero from non-zero. And we don't have `__VA_OPT__` until C++20. Maybe
there are non-portable solutions for that?)

-------------

PR Review: https://git.openjdk.org/jdk/pull/29716#pullrequestreview-3813864066
PR Review Comment: https://git.openjdk.org/jdk/pull/29716#discussion_r2816948671
PR Review Comment: https://git.openjdk.org/jdk/pull/29716#discussion_r2817063900


More information about the hotspot-dev mailing list