Stel Team
Stel Team

Reputation: 77

Why to create global objects in heap?

When i read a tutorial of ogre3d, opengl or physics framework, all the objects(Window,SceneManager object) are created in heap?

are they using heap for "the object pointer destroyed but the heap object still there(outlive a object)" ?

sorry for bad English

Upvotes: 0

Views: 81

Answers (1)

eerorika
eerorika

Reputation: 238361

There are many possible reasons:

  1. It's just incidental, and unnecessary:

    • Author didn't know any better. Not all tutorial authors are experts, nor do they necessarily hone their tutorial code to perfection.
    • Author modeled the tutorial based on a full project where it was important, but the reason was lost in the tutorial.
  2. Because the objects were big. This is argument against using automatic objects, but not really relevant for static.

  3. Because the initialization needed to be delayed.

    • This allows better error handling, and side-steps the static initialization order fiasco.
    • This could also be achieved with initialization on first use idiom that doesn't require dynamic allocation.
  4. The framework has chosen to use a special singleton pattern that relies on the singletons to be allocated dynamically, since the framework will delete them automatically. I know this is the case for Ogre::LogManager for example.

Upvotes: 3

Related Questions