是否有一种方法可以防止在构造函数中构造对象

Is there a way to prevent the object from construct in the constructor?

本文关键字:构造函数 对象 方法 一种 是否      更新时间:2023-10-16
class Date
{
private:
    int Day;
    int Month;
    int Year;
    bool CheckDate(int InputDay, int InputMonth, int InputYear);
    // this return true when the date is valid
public:
    Date(int InputDay, int InputMonth, int InputYear);
    ~Date();
};

Date::Date(int InputDay, int InputMonth, int InputYear)
{
    if (!CheckDate(InputDay, InputMonth, InputYear))
    {
        cout << "Date Invalid!n";
        this->~Date(); 
        // this invokes the destructor
        // however at the end of the program the destructor would invoke again
    }
    else
    {
        Day = InputDay;
        Month = InputMonth;
        Year = InputYear;
    }
}

我在这里找到一个资源,如果发现传递的参数是错误的,如何阻止类的对象构造?有没有办法做到毫无例外?是否有一种方法可以让构造函数检查参数本身并销毁它自己?

我建议这样做

Date::Date(int InputDay, int InputMonth, int InputYear) {
    if (!CheckDate(InputDay, InputMonth, InputYear))
        throw "Date Invalid!n";    // throw exception
    else {
        Day = InputDay;
        Month = InputMonth;
        Year = InputYear;
    }
}

另外,使用try-catch块捕获异常,并将CheckDate声明为static

正如Jerry Coffin所说,除了抛出异常之外,没有合适的方法来停止对象的构造。

唯一的选择是在你的类中有一个布尔值(valid),调用者应该在创建和删除(或重置或其他)之后测试它,如果它是假的。但是它依赖于调用者做正确的事情,而不是在类本身中处理错误条件。

异常有这个特殊的值:调用者可以捕捉到它们,如果他想,但如果他不在乎,异常确保一个构造不好的对象不会被无意中使用。

你不能在Check Date函数中调用->~Date()。在类Date函数中,一个类不能在它的函数中解构自己,它只能使用它的类。如果检查失败,可以抛出异常,不要解构类。

正如Matt所说,引发一个异常。

在另一种情况下,您可以使用指针。

考虑date类对于用户是什么样子的。

...
Date due(a,b,c);
...

如果您中途退出,则无法判断due是否无效。唯一的方法是抛出异常。

另一种方法(使用unique_ptr包装器)是创建一个函数:
unique_ptr<Date> due=makeDate(d,m,y)
unique_ptr<Date> makeDate(int d,int m,int y)
{
  if( CheckDate(d,m,y)) // make your Checkdate function static.
     return make_unique<Date>(d,m,y);
  else
     return make_unique<Date>(nullptr);
}

仔细检查这里的所有内容,我的unique_ptr语义还没有达到标准:)