If I have a simple data type as a global variable -- like a boolean flag; specifically, something that doesn't have a destructor -- does that variable remain reliable even during global destruction? Or is that not guaranteed?
For example, would the result for the following code be well-defined?
Flag.h:
void SetFlagState(bool flag);
bool GetFlagState();
Flag.cpp:
#include <Flag.h>
namespace { // local declarations
bool g_flag;
}
void SetFlagState(bool flag)
{
g_flag = flag;
}
bool GetFlagState()
{
return g_flag;
}
Main:
#include <iostream>
#include <Flag.h>
class FlagChecker
{
public:
~FlagChecker()
{
std::cout << "Flag value: " << GetFlagState() << std::endl;
}
};
FlagChecker g_FlagChecker; // global instance; dtor will be called on exit
int main()
{
SetFlagState(true);
}
Yes, this is safe. The lifetime of the storage is the duration of the program. The chief issue during that lifetime is with the moment of initialization (via your g_Flagchecker
). As there's no such thing "de-initialization" for built-in types, your g_flag
remains valid as long as there's code executing in your process.