RFR: 8255082: HotSpot Style Guide should permit noexcept [v3]

Kim Barrett kbarrett at openjdk.org
Fri Jun 20 17:29:28 UTC 2025


On Fri, 20 Jun 2025 16:53:54 GMT, Vladimir Kozlov <kvn at openjdk.org> wrote:

>> An allocation function may be declared as non-throwing (via `noexcept`).
>> 
>> If not declared non-throwing (so "potentially throwing", even though in a
>> no-exceptions build environment it won't ever actually throw, and will instead
>> probably terminate the program), the compiler's implementation of a using
>> `new` expression can assume the allocation function will never return null,
>> and does not need to generate any code to handle that possibility.
>> 
>> If declared non-throwing, a using `new` expression must account for the
>> possibility that the allocation function might return null. It needs to test
>> the result of the allocation function. If it is null then the `new` expression
>> must not call the constructor for the type and must return null as its result.
>> (Of course, usual compiler optimizations apply, and the null handling code can
>> be elided if the compiler can prove the allocation does not in fact ever
>> return null, regardless of any exception specifications. That's probably
>> pretty much never the case though.)
>> 
>> Because of that, an allocation function that can return null *must* be
>> declared non-throwing. And an allocation function that never returns null
>> shouldn't be declared non-throwing, as that's just degrading performance for
>> no reason.
>
> So we need to have explicit `nullptr` checks or `assert(p != nullprt,"")` in our code.
> 
> For example, for next `new()` we can add `assert(p != nullprt,"")` because `AllocateHeap` will exit VM if it can't allocate memory. And we should not use `noexcept` here or we can use `noexcept(false)`. Right?
> 
> 
>   ALWAYSINLINE void* operator new(size_t size, MemTag mem_tag) {
>     return AllocateHeap(size, mem_tag);
>   }

We could assert, but we don't need to. It's clutter. The usual strategy is that an allocation function
that can return null (and so must be declared `noexcept`) needs a specific argument, like the
`std::nothrow` variants, to indicate that possibility.  For such cases, if the "non-throwing" variant
isn't explicitly asked for, assume it won't ever return null.

Some of our allocators don't follow that strategy, and that's arguably unfortunate in some cases.
But an assert really isn't a good way to handle the possibility, since that means nothing in release
builds.

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

PR Review Comment: https://git.openjdk.org/jdk/pull/25574#discussion_r2159420303


More information about the hotspot-dev mailing list