gpt4 book ai didi

dynamic - 后期绑定(bind)与动态绑定(bind)

转载 作者:行者123 更新时间:2023-12-02 12:14:02 24 4
gpt4 key购买 nike

我到处都读到 Objective-C 具有真正的动态绑定(bind),而 C++ 仅具有后期绑定(bind)。不幸的是,没有一本书继续清楚地解释它或讨论底层的实现。例如,C++ 使用虚拟表。 Objective-C 怎么样?

最佳答案

http://www.gnu.org/software/gnustep/resources/ObjCFun.html有很好的描述。

基本上,动态绑定(bind)意味着在实际进行方法调用时,就决定调用哪个方法。如果您愿意,可以在此时动态选择该方法。

编辑:据我所知,这里有更多详细信息。我不保证它完全正确,但应该大部分是正确的。 Objective C 中的每个对象都是一个结构体,其第一个成员名为 isa,是一个指向类的指针。每个类本身就是一个对象,传统上的布局如下:

struct objc_class {
Class isa;
Class super_class;
const char *name;
long version;
long info;
long instance_size;
struct objc_ivar_list *ivars;
struct objc_method_list **methodLists;
struct objc_cache *cache;
struct objc_protocol_list *protocols;
};

在运行时,以下是方法查找时发生的伪代码:

Follow isa to find the class
if implementation = class.lookup_method(method):
call implementation
else if get_implementation = class.lookup_method(forwardInvocation):
implementation = get_implementation(method)
if implementation:
call implementation
else:
raise runtime error
else:
raise runtime error

lookup_method 是如何工作的?

def lookup_method (class, method):
if method in class.objc_cache:
return implementation from objc_cache
else if method in class.objc_method_list:
cache implementation from objc_method_list
return implementation
else if implementation = class.super_class.lookup_method(method):
cache implementation
return implementation
else:
return null

回答这个明显的问题,是的,这比 C++ 的虚拟表慢得多。根据基准测试,速度大约是 1/3。每一篇 Objective C 文本都紧跟这一事实:在现实世界中,方法查找速度几乎从来都不是瓶颈。

这比 C 的方法查找灵活得多。例如,您可以使用 forwardInspiration 使无法识别的方法转到变量中的对象。这种委托(delegate)可以在不知道运行时该对象的类型是什么或者它支持什么方法的情况下完成。您还可以向类添加方法 - 如果您愿意,甚至可以在运行时添加方法 - 无需访问源代码。您还可以对类和方法进行丰富的运行时自省(introspection)。

明显的另一面,任何 C++ 程序员都会上下跳动,那就是你已经放弃了编译时类型检查的任何希望。

这是否解释了差异并为您提供了足够的细节来了解发生了什么?

关于dynamic - 后期绑定(bind)与动态绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5943949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com