Consider the following lambda expression in C++11
[&] (int i)
{
if (A[i] > max)
max = A[i];
}
a) Lambda expressions, whether in c++11 or F# , require the notation of a closure . Define the concept of a "Closure" and provide an example base on the lambda expression shown above.
A closure is the outside data needed n order to execute a lambda expression . For example, in the lambda expression shown above , the lambda expression needs the array A and the variable max.
b) What closure semantics are being used in the lambda expression above?
by reference (&) sign
c) explain in more detail
A closure by reference means the lambda expression has references to the need vaiables, i,e " pointers" For variable max, this is necessary so we can change the value of max if we find larger element in the array.
d) Why did the designers of c++11 include the concept of closure semantics?
closure semantics are included in c++11 to allow programmers to control 3 thngs
1) Whether the lambda expression has access to outside data or not("none")
2)whether the lambda expression can change("&") or not change ("=") a varible declared outside the scope of the lambda. " prevent side-effects"
3) to control the copying of data that might slow down the performance
No comments:
Post a Comment