开发者

Stop C++ Class Instantiation

开发者 https://www.devze.com 2023-01-31 00:03 出处:网络
Is there a way to stop a C++ class if there is an error in the instantiation? Like, return NULL maybe? Basically I have 开发者_Python百科a wrapper class for MySQL, and the constructor does the connect

Is there a way to stop a C++ class if there is an error in the instantiation? Like, return NULL maybe? Basically I have 开发者_Python百科a wrapper class for MySQL, and the constructor does the connecting, but if the connection fails, I want the object to be, um, useless?

PDB::PDB(string _DB_IP, string _DB_USER, string _DB_PASS, string _DB_DB)
  : _DB_IP( _DB_IP ), _DB_USER( _DB_USER ), _DB_PASS( _DB_PASS ), _DB_DB( _DB_DB )
{
  mysql_init(&this->mysql);

  this->connection = mysql_real_connect(&this->mysql, this->_DB_IP.c_str(), this->_DB_USER.c_str(), this->_DB_PASS.c_str(), this->_DB_DB.c_str(), 0, 0, 0);

  if( this->connection == NULL ) // WHAT SHOULD I DO HERE, OTHER THAN THROW AN ERROR?
    {
      cout << mysql_error(&this->mysql) << endl;
    }

  this->result = NULL;
}

What should I do in the NULL test, to stop creation, etc?


Throwing an exception is really the only way to indicate an error during construction.

http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8


If the connection can normally fail, set a flag in the object and provide an is_connected() member function for the class, and use it in your application code. If it normally cannot fail, throw an exception. The former is the pattern that the C++ Standard Library uses for opening file streams.

0

精彩评论

暂无评论...
验证码 换一张
取 消