C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Opt out of multi-threading protection for static variables inside functions

From: Thiago Macieira <thiago_at_[hidden]>
Date: Sun, 27 Oct 2024 14:42:20 -0700
On Sunday 27 October 2024 13:15:35 Pacific Daylight Time Lénárd Szolnoki wrote:
> > Effectively, no, it isn't. That still registers the std::optional
> > destructor on first use, so the guard variable and all the verification
> > we've talked about is still present.
>
> Eh, right. You want to put static constinit optional into namespace or
> class scope, then do the initialization dance in your function.

That's even worse, IMO, because that causes a load-time initialisation,
whether the variable is ever used or not.

Instead, use an aligned char buffer and std::construct_at and destruct_at the
storage as you please.

> I have no idea about the implications about destruction. I have a hunch
> that this work-around is acceptable most of the time when you don't care
> about thread-safe initialization of a particular static variable.

You could also do the storage buffer and non-thread-safe checked initialisation
yourself too.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel DCAI Platform & System Engineering

Received on 2024-10-27 21:42:26