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?
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.
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; }
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.
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); }
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With