Search code examples
c++c++11

c++ late instantiation of global variable


I have code where a global resource has to be set up by quite some code:

globalClass foo;  // global variable / object; give it a memory space to live

void doSomething( void )
{
  foo.bar();      // use the global foo object
}

int main( int argc, const char *argv[] )
{
  foo( argc );   // foo can only be instantiated in main as it's using
                 // information that's only available here

  doSomething(); // use the global foo object

  return 0;
}

As you can see, foo is of global scope - but to call its constructor I need some information that's only available inside of main.

How can I achieve that?

The only solution I could figure out is to make foo a pointer to globalClass - but that would result in a pointer dereferencing each time I'm using foo. This might create a performance problem when used in a tight loop...

PS: In the real program main and doSomething would live in different files. And it's of course guaranteed that foo won't be accessed before it's instantiated.


Solution

  • How about having foo as a static variable inside a function? That way, it only gets instantiated when the function is called:

    globalClass& getThing()
    {
      static globalClass thing;
      return thing;
    }
    
    void doSomething(const globalClass& thing);
    
    int main()
    {
      const globalClass& x = getThing();
      doSomething(x);  
    }