jeudi 29 juillet 2021

Is it possible to generate a compile-time error if some member function hasn't been called

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... Well, I can do this if there is no other way...

Aucun commentaire:

Enregistrer un commentaire