Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can functions be optimized away if they have side effects?

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?

like image 704
Sam Avatar asked Jul 03 '14 17:07

Sam


1 Answers

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?

like image 132
Phil Miller Avatar answered Oct 17 '22 10:10

Phil Miller