Objective C 对象的两阶段构造

Objective C two-phase construction of objects(Objective C 对象的两阶段构造)

本文介绍了Objective 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.

我的问题是:为什么 Objective 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 及其近亲的替代品,后者是(并且将继续是,尽管没有人使用它)基于 Smalltalk 的 new 的单阶段构造函数.当 Cocoa 来到 Apple 时,+alloc 的使用已经根深蒂固,即使真的选择了你的 NSZone<,也无法回到 +new/code> 很少有重要价值.

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.

所以这不是一个大的 1 阶段/2 阶段哲学问题.实际上,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".

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

本文标题为:Objective C 对象的两阶段构造