C ++ late global variable implementation

I have code where the global resource should be configured with pretty specific 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 using // information that only available here doSomething(); // use the global foo object return 0; } 

As you can see, foo has a global scope, but to call its constructor I need information that is available only inside main .

How can i achieve this?

The only solution I could figure out is to make foo pointer to globalClass - but this will cause the pointer to be dereferenced each time foo used. This can create a performance problem when used in a closed loop ...

PS: In the real program, main and doSomething will live in different files. And he, of course, guaranteed that foo would not be available before it was created.

+6
source share
3 answers

How about having foo as a static variable inside a function? Thus, it is generated only 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); } 
+5
source

Using a pointer, as you mentioned, is the simplest and cleanest thing. The overhead of dereferencing a pointer is actually not so much. I would recommend using this if you really have not demonstrated that the overhead is noticeable.

The second option is to separate the construction and initialization of globalClass into two separate methods. The constructor would do only the simplest things that do not require external information, and you would type init(argc) or something inside main to include external information.

You can also use assignment to initialize foo, for example:

 globalClass foo; int main(int argc, const char *argv[]) { globalClass bar(argc); foo = bar; } 

which essentially uses a temporary variable to initialize, and then copies the result.

+5
source

Here's a really terrible hack if you don't want indirection and don't mind doing the cleanup yourself:

 union ClassHolder { globalClass x; char buf[sizeof globalClass]; constexpr ClassHolder() noexcept : buf() { } }; ClassHolder h; globalClass & foo = hx; int main() { new (static_cast<void *>(&h.x)) globalClass(arg1, arg2, arg3); // main program hx~globalClass(); } 
0
source

All Articles