Understanding OC/C++ Closures

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 under ARC only.

Basic understanding

Before going deeper, let’s compare the two.

Syntax

1
2
3
4
5
6
7
8
^(int x, NSString *y){} // ObjC, take int and NSString*
[](int x, std::string y){} // C++, take int and std::string

^{ return 42; } // ObjC, returns int
[]{ return 42; } // C++, returns int

^int { if(something) return 42; else return 43; }
[]()->int { if(something) return 42; else return 43; }

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
2
3
4
5
6
7
8
9
- (void)viewDidLoad {
[super viewDidLoad];

int x = 3;
void(^block)(int) = ^(int a) {
NSLog(@"%d", x);
};
block(5);
}

After clang -rewrite-objc, we get:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
struct __ViewController__viewDidLoad_block_impl_0 {
struct __block_impl impl;
struct __ViewController__viewDidLoad_block_desc_0* Desc;
int x;
__ViewController__viewDidLoad_block_impl_0(void *fp, struct __ViewController__viewDidLoad_block_desc_0 *desc, int _x, int flags=0) : x(_x) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
static void __ViewController__viewDidLoad_block_func_0(struct __ViewController__viewDidLoad_block_impl_0 *__cself, int a) {
int x = __cself->x; // bound by copy
NSLog((NSString *)&__NSConstantStringImpl__var_folders_st_jhg68rvj7sj064ft0rznckfh0000gn_T_ViewController_d02516_mii_0, x);
}

static struct __ViewController__viewDidLoad_block_desc_0 {
size_t reserved;
size_t Block_size;
} __ViewController__viewDidLoad_block_desc_0_DATA = { 0, sizeof(struct __ViewController__viewDidLoad_block_impl_0)};

static void _I_ViewController_viewDidLoad(ViewController * self, SEL _cmd) {
((void (*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("ViewController"))}, sel_registerName("viewDidLoad"));
int x = 3;
void(*block)(int) = ((void (*)(int))&__ViewController__viewDidLoad_block_impl_0((void *)__ViewController__viewDidLoad_block_func_0, &__ViewController__viewDidLoad_block_desc_0_DATA, x));
((void (*)(__block_impl *, int))((__block_impl *)block)->FuncPtr)((__block_impl *)block, 5);
}

C++ lambda uses a different mechanism. It is lowered into an anonymous C++ class. The article uses cppinsights to inspect the generated form.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <cstdio>

struct A {
int x;
int y;
};

int main()
{
A a = {1, 2};
int m = 3;
auto add = [&a, m](int n)->int {
return m + n + a.x + a.y;
};
m = 30;
add(20);
}

#include <cstdio>

struct A
{
int x;
int y;
};

int main()
{
A a = {1, 2};
int m = 3;

class __lambda_12_15
{
public:
inline int operator()(int n) const
{
return ((m + n) + a.x) + a.y;
}

private:
A & a;
int m;

public:
__lambda_12_15(A & _a, int & _m)
: a{_a}
, m{_m}
{}
};

__lambda_12_15 add = __lambda_12_15{a, m};
m = 30;
add.operator()(20);
return 0;
}

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
2
3
4
5
6
7
int x = 42;
void (^block)(void) = ^{ printf("%d\n", x); };
block(); // prints 42

__block int x = 42;
void (^block)(void) = ^{ x = 43; };
block(); // x is now 43

C++ lambdas are more flexible and support these capture forms:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[] Capture nothing 
[&] Capture any referenced variable by reference
[=] Capture any referenced variable by making a copy
[=, &foo] Capture any referenced variable by making a copy, but capture variable foo by reference
[bar] Capture bar by making a copy; don't copy anything else
[this] Capture the this pointer of the enclosing class

int x = 42;
int y = 99;
int z = 1001;
auto lambda = [=, &z] {
// can't modify x or y here, but we can read them
z++;
printf("%d, %d, %d\n", x, y, z);
};
lambda(); // prints 42, 99, 1002
// z is now 1002

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (void)viewDidLoad {
[super viewDidLoad];

int x = 3;
lambda = [&x]() -> void {
NSLog(@"x = %d", x);
};
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
lambda();
}

// The output shows that x has become a random value.
2022-02-12 23:15:01.375925+0800 BlockTest[63517:1006998] x = 32767

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
2
3
4
auto strongThis = shared_from_this(); 
doSomethingAsynchronously([strongThis, this]() {
someMember_ = 42;
});

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class CppClass {
public:
CppClass() {}
~CppClass() {}
public:
std::function<void()> callback;
};

@implementation OCClass {
std::shared_ptr<CppClass> cppObj;
}

- (void)dealloc {
NSLog(@"%s", __FUNCTION__);
}

- (instancetype)init {
if (self = [super init]) {
cppObj = std::make_shared<CppClass>();
cppObj->callback = [self]() -> void {
[self executeTask];
};
}
return self;
}

- (void)executeTask {
NSLog(@"execute task");
}
@end
1
OCClass *ocObj = [[OCClass alloc] init];

Unfortunately, this creates a retain cycle: ocObj owns cppObj, and cppObj owns ocObj through callback.

Understanding OC/C++ Closures: Capture by value (figure 1)

Looking at the generated assembly, you can see that ARC semantics are triggered during capture, so self is automatically retained.

Understanding OC/C++ Closures: Capture by value (figure 2)

These instructions increase the retain count of self:

1
2
3
0x10cab31ea <+170>: movq   -0x8(%rbp), %rdi
0x10cab31ee <+174>: movq 0x5e7b(%rip), %rax ; (void *)0x00007fff2018fa80: objc_retain
0x10cab31f5 <+181>: callq *%rax

The anonymous class parameter list shows that self is of type OCClass *, which is a pointer type.

Understanding OC/C++ Closures: Capture by value (figure 3)

So we can model the capture like this. Under ARC, it behaves like a retain:

1
2
3
4
__strong __typeof(self) capture_self = self;

// expanded
__strong OCClass * capture_self = self;

To solve the retain cycle, use __weak.

1
2
3
4
5
cppObj = std::make_shared<CppClass>();
__weak __typeof(self) wself = self;
cppObj->callback = [wself]() -> void {
[wself executeTask];
};
Understanding OC/C++ Closures: Capture by value (figure 4)

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
2
3
4
cppObj = std::make_shared<CppClass>();
cppObj->callback = [&self]() -> void {
[self executeTask];
};

The assembly no longer contains objc_retain either.

Understanding OC/C++ Closures: Capture by reference (figure 5)

Looking at the anonymous class parameter list, self is now OCClass *&, which is a reference to a pointer.

Understanding OC/C++ Closures: Capture by reference (figure 6)

So reference capture does not retain self. You can think of it like this under ARC:

1
2
3
4
__unsafe_unretained __typeof(self)& capture_self = self;

// expanded
__unsafe_unretained OCClass *&capture_self = self;

When is the captured Objective-C object released?

For this snippet:

1
2
3
4
5
auto cppObj = std::make_shared<CppClass>();
OCClass2 *oc2 = [[OCClass2 alloc] init];
cppObj->callback = [oc2]() -> void {
[oc2 class];
};
Understanding OC/C++ Closures: When is the captured Objective-C object released? (figure 7)

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:

  1. The struct constructor initializes Objective-C object fields to nil.
  2. When such a field is assigned, the old value is released and the new one is retained (or copied for blocks).
  3. When the struct destructor runs, the Objective-C field is released.

C++ lambdas can capture Objective-C objects either by value or by reference:

  1. Reference capture is roughly equivalent to __unsafe_unretained, which is dangerous because of lifetime issues.
  2. Value capture is roughly equivalent to __strong, which can create retain cycles, so __weak may 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
2
3
4
5
6
7
8
struct HMRequestMonitor  {
public:
bool WaitForDone() { return is_done_.get(); }
void SignalDone(bool success) { done_with_success_.set_value(success); }
ResponseStruct& GetResponse() { return response_; }
private:
.....
};

The upload method uses HMRequestMonitor to synchronously wait for a network response.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
hermas::ResponseStruct HMUploader::upload(
const char* url,
const char* request_data,
int64_t len,
const char* header_content_type,
const char* header_content_encoding) {
HMRequestModel *model = [[HMRequestModel alloc] init];
......

auto monitor = std::make_shared<hermas::HMRequestMonitor>();
std::weak_ptr<hermas::HMRequestMonitor> weakMonitor(monitor);
DataResponseBlock block = ^(NSError *error, id data, NSURLResponse *response) {
weakMonitor.lock()->SignalDone(true);
};
[m_session_manager requestWithModel:model callBackWithResponse:block];
monitor->WaitForDone();
return monitor->GetResponse();
}

Here we directly use std::weak_ptr.

Without __block

Understanding OC/C++ Closures: Without __block (figure 8) Understanding OC/C++ Closures: Without __block (figure 9)

From the experiment we get:

  1. The C++ object is captured by the Objective-C Block and passed by value. A breakpoint shows that the std::weak_ptr copy constructor is called.
1
2
3
4
5
6
7
8
9
template<class _Tp>
inline
weak_ptr<_Tp>::weak_ptr(weak_ptr const& __r) _NOEXCEPT
: __ptr_(__r.__ptr_),
__cntrl_(__r.__cntrl_)
{
if (__cntrl_)
__cntrl_->__add_weak();
}
  1. The weak reference count of monitor changes like this:
    • when monitor is created, weak_count = 1;
    • when weakMonitor is 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.

Note that the C++ weak count is a bit strange: its value equals weak 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
2
3
4
std::shared_ptr<hermas::HMRequestMonitor> monitor = std::make_shared<hermas::HMRequestMonitor>();
DataResponseBlock block = ^(NSError * _Nonnull error, id _Nonnull data, NSURLResponse * _Nonnull response) {
monitor->SignalDone(true);
};
1
2
(lldb) po monitor
std::__1::shared_ptr<hermas::HMRequestMonitor>::element_type @ 0x00006000010dda58 strong=3 weak=1

With __block

Can we use __block to modify the captured C++ variable? The experiment says yes.

Understanding OC/C++ Closures: With __block (figure 10) Understanding OC/C++ Closures: With __block (figure 11)

We can conclude:

  1. Objective-C Blocks can capture C++ objects by reference.
  2. The weak reference count of monitor behaves like this:
    • when monitor is created, weak_count = 1;
    • when weakMonitor is created, weak_count = 2;
    • after the Objective-C Block captures it, weak_count = 2, because a move constructor is triggered and ownership is transferred without changing the reference count.
Understanding OC/C++ Closures: With __block (figure 12)

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 monitor is:

1
2
(lldb) po &monitor 
0x0000700001d959e8

When the block assignment happens, the std::shared_ptr move constructor is called:

Understanding OC/C++ Closures: Questions about __block (figure 13) Understanding OC/C++ Closures: Questions about __block (figure 14)
  1. The this pointer inside the move constructor is 0x0000600003b0c830.
  2. __r is also 0x0000700001d959e8, which matches the original monitor address.

After the block assignment finishes, printing monitor again shows that its address has changed and now matches the this pointer from the move constructor. That means monitor has become the object constructed at that new address.

1
2
(lldb) po &monitor 
0x0000600003b0c830

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?

Understanding OC/C++ Closures: When is the captured C++ object released? (figure 15)

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 from std::enable_shared_from_this and pass its own class type as the template parameter in order to use shared_from_this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class CppClass : public std::enable_shared_from_this<CppClass> {
public:
CppClass(){}
~CppClass() {}

void attachOCBlock();
public:
OCClass2 *ocObj2;
void dosomething() {}
};

void CppClass::attachOCBlock() {
ocObj2 = [[OCClass2 alloc] init];
auto shared_this = shared_from_this();
ocObj2.ocBlock = ^{
shared_this->dosomething();
};
}
1
2
3
@interface OCClass2 : NSObject
@property void (^ocBlock)();
@end
1
2
auto cppObj = std::make_shared<CppClass>();
cppObj->attachOCBlock();

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
2
3
4
5
6
7
void CppClass::attachOCBlock() {
ocObj2 = [[OCClass2 alloc] init];
std::weak_ptr<CppClass> weak_this = shared_from_this();
ocObj2.ocBlock = ^{
weak_this.lock()->dosomething();
};
}

Conclusion

OC Blocks can capture C++ objects.

  1. If you use normal capture for a stack C++ object, the copy constructor is called.
  2. If you use __block to capture a stack C++ object, the move constructor is called, and the __block-qualified C++ 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

  1. https://isocpp.org/wiki/faq/objective-c
  2. http://www.philjordan.eu/article/mixing-objective-c-c++-and-objective-c++
  3. https://releases.llvm.org/12.0.0/tools/clang/docs/AutomaticReferenceCounting.html
  4. https://releases.llvm.org/12.0.0/tools/clang/docs/BlockLanguageSpec.html#c-extensions
  5. 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.

-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:Understanding OC/C++ Closures

Author:lingyun

Published:2022-02-14 16:25

Updated:2026-10-07 00:00

Original link:https://tsuijunxi.github.io/en/2022/02/14/understanding-objc-cpp-closures/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.