简体   繁体   中英

C++ initialization of global variables

In C++ what would be the best way to have an object that needs to be initalized in main(), but has to be global, so it can be accessed from other functions throughout the program? And make sure the destructor is called to make sure it gets cleaned up properly?

struct foo {};

foo *x_ptr;

int main() {
    foo x;
    x_ptr = &x;
    // the rest
}

You can also use std::reference_wrapper if you don't want to access members via operator-> .

But really, don't do that. Pass it along if it's needed, instead of making it global, eg

void needs_foo1(foo&);
void needs_foo2(foo&, int, int, int); 

int main() {
    foo x;
    needs_foo1(x);
    needs_foo2(x, 1, 2, 3);
    // et cetera
}

I suspect that "global" is a solution rather than a requirement. As it has been suggested you could always pass your object around explicitly.

If you don't want to do that I'd probably use a shared::ptr , possibly wrapped in a Singleton implementation. Your shared_ptr would be initialized to null at program start-up and set to a valid value in main() .

Beware that you may encounter order of destruction problems if you have global variables that depend on other global variables. There's also a huge literature about the drawbacks of the Singleton patterns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM