[英]Stop C++ Class Instantiation
Is there a way to stop a C++ class if there is an error in the instantiation? 如果实例化中存在错误,是否有办法停止C ++类? Like, return NULL maybe?
比如,返回NULL可能吗? Basically I have a wrapper class for MySQL, and the constructor does the connecting, but if the connection fails, I want the object to be, um, useless?
基本上我有一个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;
}
What should I do in the NULL test, to stop creation, etc? 我应该怎么做NULL测试,停止创建等?
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 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. 如果连接通常会失败,请在对象中设置一个标志,并为该类提供is_connected()成员函数,并在应用程序代码中使用它。 If it normally cannot fail, throw an exception.
如果通常不能失败,则抛出异常。 The former is the pattern that the C++ Standard Library uses for opening file streams.
前者是C ++标准库用于打开文件流的模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.