recently I saw a piece of code as follows :
namespace {
mutex* get_server_factory_lock() {
static mutex server_factory_lock;
return &server_factory_lock;
}
typedef std::unordered_map<string, ServerFactory*> ServerFactories;
ServerFactories* server_factories() {
static ServerFactories* factories = new ServerFactories;
// is variable factories assigned every time this function called ?
return factories;
}
} // namespace
/* static */
void ServerFactory::Register(const string& server_type,
ServerFactory* factory) {
mutex_lock l(*get_server_factory_lock());
if (!server_factories()->insert({server_type, factory}).second) {
LOG(ERROR) << "Two server factories are being registered under "
<< server_type;
}
}
It seems that function server_factories()
is similar to the singleton.
My question is : to the best of my knowledge, factories
is a static variable, and every time function server_factories()
called, this static variable will be assigned a new value. But the result is not, every time server_factories()
is called, it returns the same pointer. Why?
PS : with c++11 enabled when compiling.
Duplicated with What is the lifetime of a static variable in a C++ function?