static in a class means the object has a global lifetime (but scope local to the class). That is... all instances of the class share the same static objects.
static in local scope means the object is constructed once upon first use, then retains its value between functions calls (As if it were global, but with local scope). That is.... all calls to the function share the same static objects.
So static basically means "global lifetime, but smaller scope"
This is often combined with
const
because for constants, there is no reason to create unique copies since they'd all be the same.
For example:
1 2 3 4 5 6 7 8 9
|
void checkMyString(std::string foo)
{
static const std::string expected = "Some fixed string.";
if(foo == expected)
{
// do something
}
}
|
static makes sense here because without it, the 'expected' string will be constructed/destructed every time the function is called*. Whereas if you make it static, it's guaranteed to be constructed/destructed exactly once.
(However, note the downside here is that 'checkMyString' will no longer be threadsafe, as multiple threads may attempt to construct the string simultaneously)
* maybe... depending on compiler optimizations...