Monday, 27 March 2017

idioms - What does the code `[&]()` mean in c++?




I was poking around a Visual Studio template for a DirectX App. I came across the line m_time.Tick([&]() { ... });, and I cannot figure out what the [&]() part means. I'm not even sure if this is a stupid question because I'm pretty inexperienced in c++.



I know a [] is used for a lambda expression, but I'm not sure that makes sense. Maybe some weird delegate idiom? I don't even know. If you can point me in the direction of a list of other obscure idioms I might come across while attempting to learn c++ I would appreciate it very much.


Answer



This is an example of a lambda function.



C++ is full of obscure corners, but as odd syntax goes, lambda functions are well worth learning. The basic syntax to declare a lambda function is []() { }. This is an expression that results in an object of an implementation-defined type that can be called as if it were a function (because, somewhere in the compiler's implementation of the lambda expression syntax, it is a function).




The first advantage that this gives is that the function can be declared inline with the rest of the code, instead of having to be declared apart (which is often inconvenient for very short or specific-use functions).



The most powerful part of lambda expressions, though, is their ability to capture variables from the surrounding context: That's what the & does in your sample code. A lambda declared with [&] captures all variables (and the implicit this pointer if used inside a method) by reference. (There's also [=] to capture by value, and even an extended syntax to capture only specific variables in specific ways.)



In short, this code:



m_time.Tick([&]() { ... });



calls the Tick method on the m_time object, and passes it a lambda function that captures the surrounding context by reference. Presumably, the Tick method then calls this lambda function during its execution. Within the ..., the variables available in the scope in which the lambda was declared can be then be used -- and this capturing ability is the most powerful and convenient feature of lambdas.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...