Can functions be optimized away if they have side effects?

c++, optimization, static

Solution

The only side-effecting functions that a C++ compiler can optimize away are unnecessary constructor calls, particularly copy constructors.

Cf Under what conditions does C++ optimize out constructor calls?

Problem

I want to initialize some static data on the main thread. ``` int32_t GetFoo(ptime t) { static HugeBarData data; return data.Baz(t); } int main() { GetFoo(); // Avoid data race on static field. // But will it be optimized away as unnecessary? // Spawn threads. Call 'GetFoo' on the threads. } ``` If the complier may decide to remove it, how can I force it to stay there?

Original source

Related problems