如果实例化中出现错误,有没有办法停止C++类?比如,也许返回NULL?基本上,我有一个用于MySQL的包装类,构造函数进行连接,但是如果连接失败,我希望对象是,嗯,无用的?
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;
}在NULL测试中我应该怎么做,停止创建,等等?
发布于 2010-12-18 07:02:53
抛出异常实际上是在构造过程中指示错误的唯一方法。
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8
发布于 2010-12-18 07:04:28
如果连接通常会失败,请在对象中设置一个标志,并为该类提供一个is_connected()成员函数,然后在应用程序代码中使用它。如果正常情况下不会失败,则抛出异常。前者是C++标准库用来打开文件流的模式。
https://stackoverflow.com/questions/4475510
复制相似问题