static Database database{}; /* not recommended *//**
* This method is only secured about MT(Multi Thread)-Safe on C++11 or Higher.
*/ Database& get_database()
{
static Database databse;
return database;
}
You can think over inheritance of boost::noncopyable class if you don’t perfer to this by your hands. This way can hide all constructors except move constructor and move operator.
You can also like this
static Database& get() {
static Database* database =new Database();
return*database;
}
/* No Memory Leak, because static variable only once initializes in runtime */
Multi-Thread Safety
Skip this content. C++11 already secure it.
Well-Known Issue of Singleton
It is a situation which is A singleton object refer to another singleton object.
classDatabase {
public:virtualint get_population(const std::string& name) =0;
};
classSingletonDatabase:public Database
{
protected: SingletonDatabase() { /* Read Data from db */ }
std::map<std::string, int> capitals;
public: SingletonDatabase(SingletonDatabase const&) =delete;
voidoperator=(SingletonDatabase const&) =delete;
static SingletonDatabase& get()
{
static SingletonDatabase db;
return db;
}
intget_population(const std::string& name) override {
return capitals[name];
}
};
structSingletonRecordFinder {
inttotal_population(std::vector<std::string> names)
{
int result =0;
for (auto& name : names)
result += SingletonDatabase::get().get_population(name);
return result;
}
};
- This code can create issue, data can be changed in unit test. A solution is to make configuraion class like this.