Search code examples
clangweak-references

How does the clang implement the weak ptr?


- (void)test
{
    __weak typeof(self) weakSelf = self;
    [weakSelf test];
}

compile to

static void _I_Foo_test(Foo * self, SEL _cmd) {
 __attribute__((objc_ownership(weak))) typeof(self) weakSelf = self;
 ((void (*)(id, SEL))(void *)objc_msgSend)((id)weakSelf, sel_registerName("test"));
}

in objective-c.

The weakptr is provided by the compiler rather than some library like std::share_ptr in c++.

How does the compiler implement the weak ptr, will it be something like this.

-(void)dealloc
{
    self.weakRef = nil;
    ...
}

-(void)test
{
    self.weakRef = new WeakRef(self);
}

Solution

  • Weak pointers in Objective-C are provided by the objc runtime which is a library as well. Accessing the content of a weak pointer is done by objc_loadWeak() for instance. The clang documentation about Automatic Reference Counting explains the details.