Search code examples
c++raii

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?


Solution

  • 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, e.g.

    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
    }