如何在不使用异常的情况下检查Constructor()中的故障? [英] How can I check the failure in constructor() without using exceptions?

查看:86
本文介绍了如何在不使用异常的情况下检查Constructor()中的故障?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的所有类都具有Create()/ Destroy()(或Initialize()/ Finalized())方法。

All of the classes that I'm working on have Create()/Destroy() ( or Initialize()/Finalized() ) methods.

Create()方法的返回值为 bool ,如下所示。

The return value of the Create() method is bool like below.

bool MyClass::Create(...);

所以我可以根据返回值检查实例的初始化是否成功。

So I can check whether initialization of the instance is successful or not from the return value.

没有Create()/ Destroy()我可以在Constructor()和destructor()中完成相同的工作,但是我无法解决以下问题。

Without Create()/Destroy() I can do the same job in constructor() and destructor() but I can't solve below problem.

有人可以帮助我吗?

我不能使用异常,因为我的公司不喜欢它。

class Foo
{
private:
    AnotherClass a;
public:
    Foo()
    {
        if(a.Initialize() == false)
        {
            //???
            //Can I notify the failure to the user of this class without using exception?
        }
    }
    ...
};

Foo obj;


推荐答案

如果您不想使用例外,有两种方法可以让调用者知道构造函数是否成功:

If you don't want to use exceptions, there are two ways to let the caller know whether the constructor succeeded or not:


  1. 构造函数将引用/指针指向将进行通信的参数

  2. 该类实现了一个方法,该方法将返回构造函数的错误状态。调用者将负责检查此方法。

如果使用这两种技术,请确保您的析构函数可以处理实例构造函数失败的地方。

If you go with either of these techniques, make sure your destructor can handle an instance where the constructor has failed.

这篇关于如何在不使用异常的情况下检查Constructor()中的故障?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆