I have a situation, where I have a header/implelementation pair (x.hpp/x.cpp). Where there is a static variable with global scope defined in the x.cpp.
The header x.hpp is used in many different places within the application in question. and is also intended to be used by dlls which the application will use, either autoloading or via dlopen/LoadLibrary etc.
--- x.hpp ---
int foo();
void boo();
class fooboo
{ public: void boofoo() {} };
-------------
--- x.cpp ---
static fooboo global_var;
fooboo foo() { return global_var; }
void boo() { global_var.boofoo(); }
-------------
.
My question: In C++ is there a means by which one can guarentee under all the various use cases of how the TU(x.hpp/x.cpp) can be called and used, that only one instance of global_var exists?.
Please take into consideration multi-threaded and dll situations. Other than making sure every instance in the codebase that refers to global_var with an extern is there anything else that can be done?
As it is, the variable is only created and visible from within the x.cpp translation unit; there can only ever be one, assuming x.cpp is only ever compiled once. Including it in both a .dll and .exe would result in 2 instances of the variable, but other than that you are safe. Note though that foo() doesn't return a reference to fooboo, it returns a copy of it (and is a mis-match with the header declaration as well, by the way).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With