8

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?

Felix Glas
  • 15,065
  • 7
  • 53
  • 82
Sam
  • 19,708
  • 4
  • 59
  • 82
  • I'm cautiously optimistic that the people writing compilers are smart enough to not throw away function invocations that have side effects, just because you discard their return value. – user229044 Jul 03 '14 at 17:40
  • I'd rather appreciate some relevant section of the standard. – Sam Jul 03 '14 at 17:43
  • 1
    If your purpose is to avoid race condition (as source code comment says), you do not need the initial call. C++11 guarantees no race condition for local static variable initialization (previous versions of the standard are silent about threads). – Eugene Jul 03 '14 at 18:56
  • Consider that `printf()` has a return value, but it's usually called because of its side effects. A compiler that removed any printf call whose return value was ignored wouldn't be very popular. It would even break HelloWorld.c! – MSalters Jul 04 '14 at 08:42

2 Answers2

6

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?

Community
  • 1
  • 1
Phil Miller
  • 36,389
  • 13
  • 67
  • 90
4

Compilers must optimize according to the "as-if" rule. That is, after any optimization, the program must still behave (in the logical sense) as if the code were not optimized.

If there are side-effects to a function, any optimization must preserve the side effects. However, if the compiler can determine that the result of the side-effects don't affect the rest of the program, it can optimize away even the side-effects. Compilers are very conservative about this area. If your compiler optimizes away side-effects of the HugeBarData constructor or Baz call, which are required elsewhere in the program, this is a bug in the compiler.

There are some exceptions where the compiler can make optimizations which alter the behaviour of the program from the non-optimized case, usually involving copies. I don't think any of those exceptions apply here.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91