Commit 89b83873 authored by Rob Sherwood's avatar Rob Sherwood Committed by Facebook GitHub Bot

[easy] Add comment to ConstructorCallback explaining non-race

Summary:
There are lint rules that should discourage code from doing non-trivial
things as part of static initialization, e.g., calling a complex
constructor.

That said, probably someone somewhere in fbcode does that so I got
wrapped around the axel trying to change this code to prevent such a
race with ConstructorCallback.

The concern was that if someone created a Foo()
pre-main() there might be an initialization race for
ConstructorCallback<Foo>::nConstructorCallbacks_ and if we lost that race,
we would issue callbacks on garbage data.

BUT - apparently the C++ standard initialization requires that all static
zero values are initialized before more complex initilization, so this
can't happen (assuming the compiler correctly implements the spec).
So this code change is just to add a commment with the information so
no one else goes chasing down this (false) rat hole...

Differential Revision: D27969959

fbshipit-source-id: c135d1bb235d652d11e0541cc09a10a1bad1ce87
parent 956885e9
......@@ -85,6 +85,17 @@ class ConstructorCallback {
using This = ConstructorCallback<T, MaxCallbacks>;
explicit ConstructorCallback(T* t) {
// This code depends on the C++ standard where values that are
// initialized to zero ("Zero Initiation") are initialized before any more
// complex static pre-main() dynamic initialization - see
// https://en.cppreference.com/w/cpp/language/initialization) for
// more details.
//
// This assumption prevents a subtle initialization race condition
// where something could call this code pre-main() before
// nConstructorCallbacks_ was set to zero, and thus prevents issuing
// callbacks on garbage data.
// fire callbacks to inform listeners about the new constructor
auto nCBs = This::nConstructorCallbacks_.load(std::memory_order_acquire);
/****
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment