在初始化中引发异常时,如何防止泄漏? [英] How do you prevent leaks when raising an exception in init?

查看:63
本文介绍了在初始化中引发异常时,如何防止泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是情况.假设我有一个名为MYFoo的课程.这是初始化程序:

Here's the situation. Let's say I have a class called MYFoo. Here's it's initializer:

-init
{
  self = [super init];
  if (self)
  {
    // during initialization, something goes wrong and an exception is raised
    [NSException raise ...];
  }
  return self;
}

现在我想在其他地方使用MYFoo对象,所以我使用一种通用模式:

Now somewhere else I want to use a MYFoo object, so I use a common pattern:

MYFoo *foo = [[[MYFoo alloc] init] autorelease];

但是将要发生的是,即使在第二部分周围有try/catch,也要分配MYFoo对象,将抛出异常,错过了自动释放,并且未初始化的MYFoo对象将泄漏.

But what's going to happen is that, even if there's a try/catch around the 2nd part, a MYFoo object is going to be allocated, the exception will be thrown, the autorelease missed, and the uninitialized MYFoo object will leak.

在这里应该采取什么措施来防止这种泄漏?

What should happen here to prevent this leak?

推荐答案

The Apple Docs say the best practice is not to throw.

处理初始化失败

通常,如果有问题 在初始化方法期间,您 应该打电话给[自我释放]并返回 没有.

In general, if there is a problem during an initialization method, you should call [self release] and return nil.

如果您需要知道发生了什么,则可以init该对象并具有某种内部状态,调用者将检查该状态以确保该对象可用.

If you need to know what happened, you can init the object and have some kind of internal state that gets checked by the caller to ensure the object is usable.

这篇关于在初始化中引发异常时,如何防止泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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