You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 104c483
Browse filesBrowse the repository at this point in the historyBrowse files
[unsafe] Fix non-const global initializers and [unsafe, refcount] order of global initialization (#366)
Rust requires initializers of global variables to be const. C++ does not
require that.
To fix this tension, wrap global variables in `std::cell::LazyCell` so
that initialization does not depend on the constness of the initializer.
Another problem that this PR fixes is the moment when global variables
are initialized in both refcount and unsafe. `thread_local` in refcount
and the new `LazyCell` in unsafe initialize the variable on the first
usage. This is wrong if the constructors of the global variables have
side effects that must be visible in the program, for example:
```cpp
#include <cassert>
static int total = 0;
struct S {
S(int x) { total += x; }
};
// there is no explicit usage of a and b inside the program other than the initialization
// however the constructor has side effects that are visible on the total variable
// so the initialization has to happen before entering main, not lazily as thread_local
// and LazyCell normally do
static S a(1);
static S b(10);
int main() {
assert(total == 11);
return 0;
}
```
To fix this, I added a new function that runs before main and forces the
initialization of global variables: `__cpp2rust_init_globals()`.
---------
Co-authored-by: Nuno Lopes <nuno.lopes@tecnico.ulisboa.pt>
0 commit comments