10

I recently read some C++ code like this:

setData(total, &user, ^() {
  struct dst_t to = {ip, port};
  sendData(to, data);
});


getData(total, ^{
  recvData(data, NULL);
});

I've never seen ^() {} nor ^{}. What do they mean? Some kind of anonymous function?

Boann
  • 48,794
  • 16
  • 117
  • 146
vego
  • 889
  • 1
  • 8
  • 20

1 Answers1

3

It's hard to find a duplicate with ^() {} symbols, so I'll post an answer.

These are "blocks", which is a clang compiler extension that creates lambda-like closures.

More info at wiki and in clangs Language Specification for Blocks.

When there is an empty argument list, the (void) can be omitted, the ^ { recvData(data, NULL); } is the same as ^ void (void) { recvData(data, NULL); }.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 3
    Note that while they work in C & C++ code, they were primarily designed around an objective-c world, and if you're using C++, you should almost certainly use the much more idiomatic lambdas and std::function instead of these (though note that [std::function can hold blocks](https://stackoverflow.com/questions/11669292/objective-c-11-why-cant-we-assign-a-block-to-a-lambda)) – Richard J. Ross III Nov 26 '19 at 00:52