Background
Apple’s Objective-C compiler lets you mix C++ and
Objective-C in the same source file. The combined language
is Objective-C++. Compared with ecosystems where
Swift, Kotlin, or Dart have to
bridge into C++ through separate files and interop layers
such as JNI or FFI, the single-file
Objective-C and C++ mix is very pleasant.
That said, mixed compilation does not mean the two languages gain
each other’s features. Objective-C++ does not add C++
features to Objective-C, and it does not add Objective-C features to
C++. For example, you cannot call a C++ object with Objective-C syntax,
you cannot add a constructor or destructor to an Objective-C object, and
you cannot swap this and self.
The class systems remain separate: C++ classes cannot inherit from Objective-C classes, and Objective-C classes cannot inherit from C++ classes.
This article explores the confusing interaction between Objective-C
Blocks and C++ lambdas.
Environment:
C++14, Objective-C underARConly.
Basic understanding
Before going deeper, let’s compare the two.
Syntax
1 | ^(int x, NSString *y){} // ObjC, take int and NSString* |
Principle
For a detailed explanation of Objective-C Blocks, see A Deep Dive into Block Variable
Capture and __block. Here we expand only enough
generated code to compare the two models.
1 | - (void)viewDidLoad { |
After clang -rewrite-objc, we get:
1 | struct __ViewController__viewDidLoad_block_impl_0 { |
C++ lambda uses a different mechanism. It
is lowered into an anonymous C++ class. The article uses
cppinsights to inspect the generated form.
1 |
|
The lambda expression add is converted into
class __lambda_12_15, and the call to add is
converted into a call to add.operator().
Captured variables
The two constructs both capture variables, but the capture rules and generated types are different.
Objective-C Blocks can capture variables only in the
normal way or through __block:
1 | int x = 42; |
C++ lambdas are more flexible and support
these capture forms:
1 | [] Capture nothing |
Memory management
Objective-C blocks participate in ARC and object lifetime rules, while C++ lambdas follow normal C++ object semantics.
Objective-C Blocks and C++
lambdas both start life as stack objects, but they evolve
differently afterwards. An Objective-C Block is essentially
an Objective-C object. It is stored by reference and never by value. To
extend its lifetime, a Block must be copied to the heap.
Objective-C Blocks follow Objective-C reference-counting
rules: copy and release must be balanced, and
the same applies to Block_copy and
Block_release. The first copy moves the Block
from the stack to the heap; later copies increment its reference count.
When the reference count reaches zero, the Block is
destroyed and the captured objects are released.
C++ lambdas are stored by value, not by
reference. Captured variables become member variables of the anonymous
class object. When the lambda expression is copied, those captured
variables are copied too, with the proper constructors and destructors
involved. One extremely important point is reference capture: referenced
variables are stored as references inside the anonymous object and do
not receive any special lifetime treatment. This means that after the
original variable lifetime ends, the lambda may still access it, causing
undefined behavior or a crash:
1 | - (void)viewDidLoad { |
By comparison, the object pointed to by this is stored
on the heap, so its lifetime is somewhat more stable, but it is still
not absolutely safe. In some cases, smart pointers are needed to extend
the lifetime:
1 | auto strongThis = shared_from_this(); |
Mixed capture problems
How does
C++ lambda capture Objective-C objects?
Capture by value
Suppose an OCClass instance owns a
std::shared_ptr<CppClass>, and that C++ object stores
a callback lambda. Inside the lambda, we capture self by
value.
1 | class CppClass { |
1 | OCClass *ocObj = [[OCClass alloc] init]; |
Unfortunately, this creates a retain cycle: ocObj owns
cppObj, and cppObj owns ocObj
through callback.
Looking at the generated assembly, you can see that ARC semantics are
triggered during capture, so self is automatically
retained.
These instructions increase the retain count of
self:
1 | 0x10cab31ea <+170>: movq -0x8(%rbp), %rdi |
The anonymous class parameter list shows that self is of
type OCClass *, which is a pointer type.
So we can model the capture like this. Under ARC, it behaves like a retain:
1 | __strong __typeof(self) capture_self = self; |
To solve the retain cycle, use __weak.
1 | cppObj = std::make_shared<CppClass>(); |
Looking at the assembly again, the objc_retain logic is
gone and objc_copyWeak appears instead.
Capture by reference
What if we capture self by reference instead?
1 | cppObj = std::make_shared<CppClass>(); |
The assembly no longer contains objc_retain either.
Looking at the anonymous class parameter list, self is
now OCClass *&, which is a reference to a pointer.
So reference capture does not retain self. You can think
of it like this under ARC:
1 | __unsafe_unretained __typeof(self)& capture_self = self; |
When is the captured Objective-C object released?
For this snippet:
1 | auto cppObj = std::make_shared<CppClass>(); |
When CppClass is destroyed, its
std::function is destroyed too, and that in turn releases
the captured Objective-C object oc2.
Conclusion
C++ lambdas are essentially anonymous struct types that
store captured variables. ARC ensures that C++ structs
containing Objective-C object fields still follow ARC semantics:
- The struct constructor initializes Objective-C object fields to
nil. - When such a field is assigned, the old value is released and the new one is retained (or copied for blocks).
- When the struct destructor runs, the Objective-C field is released.
C++ lambdas can capture Objective-C objects either by
value or by reference:
- Reference capture is roughly equivalent to
__unsafe_unretained, which is dangerous because of lifetime issues. - Value capture is roughly equivalent to
__strong, which can create retain cycles, so__weakmay be needed.
How does an Objective-C Block capture C++ objects?
Now let’s look at the reverse direction: how Objective-C
Blocks capture C++ objects.
In the code below, HMRequestMonitor is a
C++ struct. Its WaitForDone and
SignalDone methods are used to implement
synchronization.
1 | struct HMRequestMonitor { |
The upload method uses HMRequestMonitor to
synchronously wait for a network response.
1 | hermas::ResponseStruct HMUploader::upload( |
Here we directly use std::weak_ptr.
Without __block
From the experiment we get:
- The
C++object is captured by the Objective-CBlockand passed by value. A breakpoint shows that thestd::weak_ptrcopy constructor is called.
1 | template<class _Tp> |
- The weak reference count of
monitorchanges like this:- when
monitoris created,weak_count = 1; - when
weakMonitoris created,weak_count = 2; - after the Objective-C block captures it,
weak_count = 4, because the weak pointer is copied twice:- once during capture;
- once more when the block is copied from stack to heap.
- when
Note that the
C++weak count is a bit strange: its value equalsweak references + 1. The reason is a bit involved; see https://stackoverflow.com/questions/5671241/how-does-weak-ptr-work
If we do not use std::weak_ptr and instead capture
std::shared_ptr directly, the strong reference count
becomes 3, and the logic is otherwise the same.
1 | std::shared_ptr<hermas::HMRequestMonitor> monitor = std::make_shared<hermas::HMRequestMonitor>(); |
1 | (lldb) po monitor |
With __block
Can we use __block to modify the captured C++ variable?
The experiment says yes.
We can conclude:
- Objective-C
Blocks can captureC++objects by reference. - The weak reference count of
monitorbehaves like this:- when
monitoris created,weak_count = 1; - when
weakMonitoris created,weak_count = 2; - after the Objective-C
Blockcaptures it,weak_count = 2, because a move constructor is triggered and ownership is transferred without changing the reference count.
- when
Questions about
__block
Readers familiar with C++ may wonder: if the move constructor is
triggered and ownership is transferred, does that mean
monitor becomes nullptr and is effectively
destroyed? Why can the sample still access monitor
afterwards?
Let’s verify it.
After the first line below executes, the address of
monitoris:
1 | (lldb) po &monitor |
When the block assignment happens, the
std::shared_ptrmove constructor is called:
- The
thispointer inside the move constructor is0x0000600003b0c830. __ris also0x0000700001d959e8, which matches the originalmonitoraddress.
After the block assignment finishes, printing
monitoragain shows that its address has changed and now matches thethispointer from the move constructor. That meansmonitorhas become the object constructed at that new address.
1 | (lldb) po &monitor |
During the whole process, the monitor variable changes
address and becomes a different std::shared_ptr object, so
it can still be accessed afterward.
When is the captured
C++ object released?
When the Objective-C Block is released, the captured
C++ object is released as well.
Capturing
shared_from_this
C++’s this is just a pointer, so capturing
it in an Objective-C Block is not fundamentally different
from capturing an integer. The interesting case is
shared_from_this, which is the smart-pointer version of
this.
A
C++class must inherit fromstd::enable_shared_from_thisand pass its own class type as the template parameter in order to useshared_from_this.
1 | class CppClass : public std::enable_shared_from_this<CppClass> { |
1 | @interface OCClass2 : NSObject |
1 | auto cppObj = std::make_shared<CppClass>(); |
From the earlier conclusion, capturing shared_from_this
directly inside attachOCBlock also creates a retain cycle,
so we should use std::weak_ptr instead:
1 | void CppClass::attachOCBlock() { |
Conclusion
OC Blocks can capture C++
objects.
- If you use normal capture for a stack
C++object, the copy constructor is called. - If you use
__blockto capture a stackC++object, the move constructor is called, and the__block-qualifiedC++object gets redirected during capture.
Summary
We compared Objective-C Blocks and C++ lambdas in four
areas: syntax, implementation, capture rules, and memory management. The
mixed-language examples then showed where those two ownership models
meet and where retain cycles or dangling references can appear.
The details matter because mixed Objective-C++ code crosses two independent object and lifetime models. Understanding the generated structures and ownership transitions is more reliable than debugging each capture problem by trial and error.
References
- https://isocpp.org/wiki/faq/objective-c
- http://www.philjordan.eu/article/mixing-objective-c-c++-and-objective-c++
- https://releases.llvm.org/12.0.0/tools/clang/docs/AutomaticReferenceCounting.html
- https://releases.llvm.org/12.0.0/tools/clang/docs/BlockLanguageSpec.html#c-extensions
- https://mikeash.com/pyblog/friday-qa-2011-06-03-objective-c-blocks-vs-c0x-lambdas-fight.html
Source note: this article also appears on WeChat: Understanding OC/C++ Closures.