Atomic<> static construction issue



static Atomic <int> s_val;

There is no way to assure that s_val will be initialized to zero before any other constructors for objects with static storage duration runs. This is because the Atomic ctor assigns value to zero.


But what else could possibly be done about that?


Using Static::Storage, which relies on C++ spec N2914=09-0104 (explained in the comments at the top of that file)

Static::Storage <Atomic <ProtectedCall::Handler const*>, ProtectedCall>

s_handler is guaranteed to be bitwise initialized to zero before an code executes (especially constructors for objects with static storage duration) I covered this issue a while back.

Yeah it’s true, I’m depending on Atomic<> to have only primitive types as members.

This is important because I want to be able to have a handler for unhandler exceptions installed even before main() is called, to catch exceptions thrown by constructors of objects with static storage duration.


I hear you, but I also think that since the Atomic class is a POD with a trivial constructor, it seems vanishingly unlikely that any compiler would actually fail to just treat it like a primitive static variable. I could be wrong about that, but can’t see any other way to change the Atomic class itself to fix it anyway - it’s the place where the static is declared that would need to be changed.

Have you considered a trick like this?

union SneakyUnion { int dummy; Atomic<int> atomic; }; static SneakyUnion staticAtomic = { 0 };


Yes you’re right on most of that. But no, a compiler is not obligated to mark the memory for those objects as “zero fill” to the linker, like it does for primitives. If you depend on that then of course you may sometimes get undefined behavior.

Neat trick with the union but my solution is cooler, it’s a little tighter interface-wise.


No it’s not. It’s based on some obscure - offlist comment that no-one reads.
The union code at least is usual to any C and C++ programmer, it’s what BSS section is made for, and all executable format that Juce is designed for support this section, so it’ll work on all platform Juce is designed for.

BTW, you’re over reacting about the static initialization order issue, if you are writing so many static object that it proves a problem in your application, then you should learn to use the linker option & attribute / pragma to put your static object in the expected order, it’ll make your code easier to read and understand for someone not aware of your obsessions.