简体   繁体   English

Apple Blocks vs C ++ 11 Lambdas

[英]Apple Blocks vs C++11 Lambdas

I"ve been playing around with C++11 and Apple blocks, and I've tried to create sort of an interator function. The code: 我一直在玩C ++ 11和Apple块,我试图创建一种interator函数。代码:

#include <functional>
#include <stdio.h>

void range(int low, int high, int& ref, std::function<void(void)> block){
    int a = low;
    while(a < high){
        ref = a;
        block();
        a++;
    }
}

void range(int low, int high, int& ref, void (^block)(void)){
    int a = low;
    while(a < high){
        ref = a;
        block();
        a++;
    }
}

int main(){
    int a = 0;
    range(0, 5, a, [&](){
        printf("%i\n", a);
    });

    int b = 0;
    range(0, 5, b, ^(){
        printf("%i\n", b);
    });
}

The first one, using C++11 Lambdas worked as I expected, and gives the following output 第一个,使用C ++ 11 Lambdas按预期工作,并给出以下输出

0
1
2
3
4

The second one, using the Apple Blocks API, gives 5 zeroes, is there any way to make it work for blocks too? 第二个,使用Apple Blocks API,提供5个零,是否有任何方法可以使它适用于块?

Quoting from the source directly: 直接从来源引用:

Only the value is captured, unless you specify otherwise. 除非另行指定,否则仅捕获值。 This means that if you change the external value of the variable between the time you define the block and the time it's invoked, the value captured by the block is unaffected. 这意味着如果在定义块的时间和调用块的时间之间更改变量的外部值,则块捕获的值不受影响。

The value captured is a copy of int b which has an initial value of 0 . 捕获的值是int b的副本,其初始值为0

Then they go on to specify: 然后他们继续说明:

If you need to be able to change the value of a captured variable from within a block, you can use the __block storage type modifier on the original variable declaration. 如果需要能够在块中更改捕获变量的值,则可以在原始变量声明上使用__block存储类型修饰符。

And they provide the following code sample: 他们提供以下代码示例:

__block int anInteger = 42;

void (^testBlock)(void) = ^{
    NSLog(@"Integer is: %i", anInteger);
};

anInteger = 84;
testBlock(); // Prints "Integer is: 84"

I advise you to stick with Lambdas. 我建议你坚持使用Lambdas。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM