目标C对象的两阶段构造 [英] Objective C two-phase construction of objects

查看:179
本文介绍了目标C对象的两阶段构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在读RAII和单相或两相构造/初始化。不管出于什么原因,我一直在两个阶段直到最近,因为在某些时候,我必须听说,在你的构造函数中做错误操作是不好的。但是,我想我现在相信单相是更好的,基于我阅读的SO和其他文章。

I've been reading up on RAII and single vs. two-phase construction/initialization. For whatever reason, I was in the two-phase camp up until recently, because at some point I must have heard that it's bad to do error-prone operations in your constructor. However, I think I'm now convinced that single-phase is preferable, based on questions I've read on SO and other articles.

我的问题是:为什么目标C使用两阶段方法(alloc / init)几乎只用于非方便构造函数?在语言中有什么特别的原因,还是只是设计师的设计决定?

My question is: Why does Objective C use the two-phase approach (alloc/init) almost exclusively for non-convenience constructors? Is there any specific reason in the language, or was it just a design decision by the designers?

推荐答案

我有令人羡慕的情况为那些在1991年写了 + alloc 的人工作,我几个月前碰巧问他一个非常相似的问题。添加 + alloc 是为了提供 + allocWithZone:,这是为了在NeXTSTEP中添加内存池2.0,其中内存非常紧张(4M)。这允许调用者控制对象在内存中的分配位置。它是一个替代 + new 和它的亲,这是(并继续是,虽然没有人使用它)1阶段构造函数,基于Smalltalk的 new 。当可可来到苹果,使用 + alloc 已经根深蒂固,没有回到 + new

I have the enviable situation of working for the guy who wrote +alloc back in 1991, and I happened to ask him a very similar question a few months ago. The addition of +alloc was in order to provide +allocWithZone:, which was in order to add memory pools in NeXTSTEP 2.0 where memory was very tight (4M). This allowed the caller to control where objects were allocated in memory. It was a replacement for +new and its kin, which was (and continues to be, though no one uses it) a 1-phase constructor, based on Smalltalk's new. When Cocoa came over to Apple, the use of +alloc was already entrenched, and there was no going back to +new, even though actually picking your NSZone is seldom of significant value.

即使实际选择您的 NSZone 很少有价值。相/两相哲学问题。在实践中,Cocoa有一个单阶段构造,因为你总是在一个单独的调用中,而不是在 + alloc 。你可以把它看作是一种详细的输入new的方法。

So it isn't a big 1-phase/2-phase philosophical question. In practice, Cocoa has a single phase construction, because you always do (and always should) call these back-to-back in a single call without a test on the +alloc. You can think of it as a elaborate way of typing "new".

这篇关于目标C对象的两阶段构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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