开发者

If exception handling is not allowed, How object construction of a class can be stopped if parameter passed is found wrong?

开发者 https://www.devze.com 2023-03-25 06:18 出处:网络
class Date { Date(int day, int month, int year) {} } int main() { Date d = Date(100, 2, 1990); } Here value(100) passed to day is not right, My question is how \'day\' parameter can be checked in co
class Date
{
    Date(int day, int month, int year) {     }
}
int main()
{
    Date d = Date(100, 2, 1990);
}

Here value(100) passed to day is not right, My question is how 'day' parameter can be checked in constructor to prevent creation of object. Please note exception handlin开发者_JAVA技巧g is not allowed


One of the arguments often leveled against modern C++ programming techniques like RAII is that they can't be used in the absence of exceptions, since exceptions are the only way to signal a constructor's failure. And that's absolutely true.

The only way to deal with an environment where exceptions are not allowed is to take initialization out of the constructor. Do it in a member function or something.

Just remember: environments without exceptions are not true C++. You have to treat them more like C-with-classes.


Once I talked to software engeeners who had been dveloping on eCos a C++ project and did not have C++ exceptions supported by the compiler. As a result they did not use throwing exceptions in constructors.

They approach was to use simple constructors like this

Date::Date()
 :
 initialized_ (false)
{}

and then init function was always used:

bool Date::init(int day, int month, int year)
{
    // return false if there is an error while initializing the object
    // return true if there is no error
    initialized_ = true;

}

They always checked the result of init() functions.

0

精彩评论

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