Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do ^() {} and ^{} mean in C++?

Tags:

c++

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?

like image 384
vego Avatar asked Nov 26 '19 00:11

vego


People also ask

What do {} mean in C?

It is called block and it is language-level addition to C and Obj-C. It is a function that treated like an object. Those, it is implementation of closure concept in C. Adds more functional programming flavour. You can find syntax and usage practice recommendations in this article.

What does ':' mean in C++?

Its technical name is the conditional operator, and it's shorthand for if-then;else . if m > n then m else n. or in actual C++ syntax: if(m > n) { return m; } else { return n; }

What does &var mean in C++?

The & symbol in a C++ variable declaration means it's a reference. It happens to be a reference to a pointer, which explains the semantics you're seeing; the called function can change the pointer in the calling context, since it has a reference to it.


1 Answers

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); }.

like image 51
KamilCuk Avatar answered Oct 21 '22 15:10

KamilCuk