Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Dec 14, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Avoiding Deferment of Global Object Construction

Consider the following class and its global instance:

// Foo.h
  class Foo
    Foo()  { RegisterSelf(); }
    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.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date