Dean Dean - 13 days ago 6
C++ Question

Where is a static local variable object of function defined?

I know that static member variables have to be defined out of the class somewhere (not in a header - in a TU), but I'm wondering then why the following works

#include <iostream>

class Logger {
public:
static const Logger& GetInstance() {
static Logger logger; // ??
return logger;
}

void hello() const {
std::cout << "Hello";
}

private:
Logger() {

}
};


const Logger& logger = Logger::GetInstance();

int main(int argc, char* argv[]) {

logger.hello();

return 0;
}


Where is the object associated with
logger
defined? And why doesn't a function static variable require a definition/instantiation point as for a static class member variable?

Answer

You do define it: in the function GetInstance().

It's just that luck is on your side: that function is only encountered in exactly one translation unit (you've put the class definition in a source file), so the linker is not going to moan.

It would have been a different matter if the code were in a header and included in more than one translation unit.