【问题标题】:Is there a way to prevent the object from construct in the constructor?有没有办法防止对象在构造函数中构造?
【发布时间】:2015-10-11 19:38:37
【问题描述】:
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;
    }
}

我在这里找到资源How can object construction of a class be stopped if a parameter passed is found to be wrong?。 有没有办法无一例外地做到这一点? 有没有办法让构造函数检查参数本身并自行销毁?

【问题讨论】:

  • 调用者如何检查这个?如果类转换为bool 和/或operator!,则您的代码已经编译并且不正确。如果调用者不检查怎么办?
  • 没有。事实上,这是向 C++ 添加异常处理的最大动机之一。
  • 我会提出一个例外。我不会这样做。
  • 抛出异常。这就是他们的目的。
  • @JerryCoffin 谢谢。你的回答是最简单最准确的。

标签: c++ constructor destroy


【解决方案1】:

我建议这个

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

【讨论】:

    【解决方案2】:

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

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

    异常有这个特殊的价值:调用者可以根据需要捕获它们,但如果它不关心,异常确保不会无意中使用构造错误的对象。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        正如马特所说,引发异常。

        在替代方案中,您可以使用指针。

        考虑用户对日期类的看法。

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

        如果中途退出,则无法判断到期是否无效。 唯一的办法就是抛出异常。

        另一种方法(使用 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 语义还没有达到鼻烟:)

        【讨论】:

          猜你喜欢
          • 2018-09-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-23
          • 1970-01-01
          • 1970-01-01
          • 2019-07-13
          • 2021-11-11
          相关资源
          最近更新 更多