Avoiding Deferment of Global Object Construction

Consider the following class and its global instance:

 // Foo.h  class Foo  {  public:    Foo()  { RegisterSelf(); }  private:    void RegisterSelf() {/**/}  };// Foo.cpp  #include "Foo.h"  Foo reg;  // global instance// main.cpp  #include "Foo.h"  int main()  {  }

The global object reg may be optimized away during the link phase, even when all compiler and linker optimizations are turned off — to the surprise of the programmer. What is going on here? According to the C++ standard, the construction of an object defined in a namespace scope (a global object is considered as such) can be “deferred” indefinitely if the following conditions hold true: 1. No other function or object defined in the same translation unit refers to that global object.2. The global object’s constructor has no side effects.

In other words, the linker is allowed (but is not required) to remove the construction of object reg from the program because no reference to reg is made by another object or function which would cause reg to be initialized, and because reg’s constructor has no side effects.

In order to force the linker to construct reg, you must refer to it somewhere in your program. Alternatively, you can add an operation with a side effect to reg’s constructor, such as calling printf() from it.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: