I'm coding a class with Singleton pattern.
class GroupListDAO {
public:
static GroupListDAO* getInstance() {
static GroupListDAO groupListDAO;
return &groupListDAO;
}
init(server::mysqldb::MysqlHelperTempalte* pHelper) {
mysqlHT = pHelper;
}
bool getUserHeartNum(uint32_t owner, uint32_t& totalNum);
bool setUserHeartNum(uint32_t owner, uint32_t totalNum, uint32_t update_time);
private:
MysqlHelperTempalte *mysqlHT;
GroupListDAO() = default;
~GroupListDAO() = default;
};
As you see, this class is used to connect to Mysql. So the member data mysqlHT must be initialized before calling any other member functions.
In a word, the class user must use this class as below:
GroupListDAO *p = GroupListDAO::getInstance();
p->init(XXX); // init must be called before calling any other member functions
p->getUserHeartNum(...);
p->setUserHeartNum(...);
So I'm thinking if there is a way to force the class user to call the function init. Meaning that if the class user codes like this:
GroupListDAO *p = GroupListDAO::getInstance();
p->getUserHeartNum(...);
p->setUserHeartNum(...);
Some compile-time error can be generated.
Ofc, you might say that we can if (mysqlHT == nullptr) { throw exception; } in other member functions, but that would be runtime error, instead of compile-time error.
REAL CASE
One large project is developed by 5 developers. They are all using some Singleton objects. But they must say: Hey, I've initialized that, you guys can use it in your codes. Or, we are sorry, we all forget to initialize it...