Disable capturing strong self in closures

Hello,

I suggest returning an error or in the worst case a warning for developers using strong references to self inside of closure body which causes many memory leaks.

I think this can be mitigated using Thread Sanitizer, which IIRC thanks to @Aciid is now working for Linux as well.

But I would like this to be an option in the compiler. I've had a good couple of leaks because of this :sweat_smile:. --no-closure-capturing-strong-self?

There are definitely times when strong capturing of self is valuable. That said I think an optional warning flag would be great.

I would not want this warning on by default. Perhaps adding it to the static analyzer would be a better choice. I have many classes which are intended to exist for the duration of a program (you could call them singletons in practice). There is nothing unsafe about strong references to these instances in closures, because they are intended to never be deallocated anyway.

Additionally, strong references are only going to cause leaks if the closure is itself retained indefinitely. This kind of analysis is what the static analyzer already does.

3 Likes