[cfe-dev] [LLVMdev] Error prone default memory capturing convention of blocks.

John McCall rjmccall at apple.com
Tue Oct 2 23:14:29 PDT 2012


On Oct 2, 2012, at 10:26 AM, Jim Grosbach wrote:
> On Oct 2, 2012, at 8:35 AM, Iaroslav Pavlov <iaroslav.pavlov at gmail.com> wrote:
> 
>> Hi guys,
>> 
>> I've been using blocks for a while and found that current behavior is error prone. So I am going to propose to you the better one.
>> 
>> Motivation:
>> 
>> 1) The __weak variables in blocks are very common pattern. So having any implicit default behavior makes thing worse.
>> 2) Some stupid mistakes like: 
>> 
>> __weak typeof (self) theSelf = self;
>> 
>> ...^ {
>> 	theSelf.blabla = ..
>> 	....
>> 	
>> 	[self blabla];  // ups, calling self directly is an error
>>         _ivar = … // or implicit call to self.
>> }
>> 
>> Retain cycles are very hard to find. I am not saying about trivial ones, that compiler can find, or the Leaks tool. Recently I have 3 retain cycles in my program, no one appeared in Leaks. So the main point is prevent such errors at first place, not to rely on that tool will find it. 
>> 
>> Proposition: 
>> 
>> Any variable captured in block must have explicit qualifier to specify memory capturing semantic: __retain, __weak, __unsafe_unretained. Qualifier is obligatory, no defaults allowed.
>> 
>> Code will look something like this:
>> 
>> 1) 
>> NSString* theLocalVariable = …
>> 
>> ...^ {
>> 	...
>> 	__weak self;
>> 	self.blabla  =  ...
>>>> 
>> 	[self blabla:(__retain theLocalVariable)];
>> }
>> 
>> 2)
>> {
>> 	self.blabla = … // compile error: missing memory capture semantic qualifier.
>> 	....
>> }
>> 
>> For __block qualifier I propose to leave old behavior (leave the default __retain semantic), because retain cycles with write-to variables are uncommon.

This is an interesting idea, and we've been looking at several similar ones.  I encourage you to file a bug at the Apple bug reporter.

John.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20121002/0770d3ff/attachment.html>


More information about the cfe-dev mailing list