C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Catch exception thrown from constructor of global object

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Thu, 12 Jan 2023 11:17:03 -0500
On Thu, Jan 12, 2023 at 10:34 AM Federico Kircheis via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> On 2023-01-12 at 11:23, Frederick Virchanza Gotham via Std-Proposals
> wrote:
>
> >
> >Now if you were to ask me . . . . I would almost go so far as to
> >propose that C++26 should deprecate defining a global object that
> >doesn't satisfy 'is_trivial' so that all such objects would be wrapped
> >in an std::optional<T> and emplaced within the body of 'main', but of
> >course I know that I won't get any support on that.
>
>
> It would also not cover most use-cases, for example
>
>
> ----
> /* const */ int i = function_that_throws();
>
> int main(){
> }
> ----
>
>
> Also std::optional as global variable is problematic if inside a
> library, depending on the visibility of the symbols, the destructor
> might be executed more than once (and thus be UB)

It seems to me that, to the extent that this is a significant problem,
static analysis is likely the most effective solution. Static analysis
tools should be able to detect if the initializer for a global is
`noexcept` and there can be options to have such tools give a warning
if it isn't. Better tools might be able to follow inlined functions to
see if anything could actually throw given the value of parameters.

There's no need for a complex language change. Especially since more
pernicious problems of complex global initialization (the static
initialization order fiasco) also need attention from static analysis
tools. This would just be one more to throw on the pile.

Received on 2023-01-12 16:17:08