Objective-C ++ 11-为什么我们不能为lambda分配一个块? [英] Objective-C++ 11 - Why can't we assign a block to a lambda?
问题描述
因此,我刚刚升级到Xcode 4.4,并且在变更日志中注意到了:
So, I just upgraded to Xcode 4.4, and I noticed in the changelog:
Apple LLVM编译器支持其他C ++ 11功能,包括lambdas
Apple LLVM compiler supports additional C++11 features, including lambdas
哪个很棒!所以我开始编码,然后发现了一些东西:
Which is awesome! So I got around to coding, and I found a few things out:
-
Lambda可分配给Objective-C块:
Lambdas are assignable to Objective-C blocks:
void (^block)() = []() -> void {
NSLog(@"Inside Lambda called as block!");
};
block();
std::function
可以容纳一个Objective-C块:
std::function
can hold an Objective-C block:
std::function<void(void)> func = ^{
NSLog(@"Block inside std::function");
};
func();
我们无法为Lambda分配一个Objective-C块:
We cant assign an Objective-C block to a lambda:
auto lambda = []() -> {
NSLog(@"Lambda!");
};
lambda = ^{ // error!
NSLog(@"Block!");
};
lambda();
这是为什么?鉴于我们上面已经看到的内容,两者在语义上是否应该等效吗?
Why is this? Shouldn't the two be semantically equivalent, given what we've seen above?
推荐答案
明确禁用了C ++ 11的lambda的复制分配运算符 1 .这不是语义上等效"的问题.它甚至无法分配回自己.更不用说无关的类型了.
C++11's lambda's copy-assignment operator is explicitly disabled1. This is not a matter of "semantically equivalent". It can't even assign back to itself. Not to mention an unrelated type.
#include <cstdio>
#include <type_traits>
int main() {
auto lambda1 = []() -> void { printf("Lambda 1!\n"); };
lambda1 = lambda1; // error: use of deleted function ‘main()::<lambda()>& main()::<lambda()>::operator=(const main()::<lambda()>&)’
return 0;
}
std::function
可以容纳一个Objective-C块.
std::function
can hold an Objective-C block.
-
std::function
可以保存任何可以作为f(a,b,c,...)
调用的类型.由于块支持"invoke运算符",因此它也可以由std::function
保留.但是请注意,Objective-C和C ++遵循不同的内存管理方案,因此长时间将块存储在std::function
中可能会导致引用悬空.
std::function
can hold any types which can be invoked asf(a,b,c,...)
. Since blocks support "the invoke operator", it can also be held by astd::function
. But notice that Objective-C and C++ follow different memory management scheme, so storing a block in astd::function
for a long time may cause dangling reference.
Lambda可分配给Objective-C块:
Lambdas are assignable to Objective-C blocks:
- 责备 SAHChandler 2 :).但是,尚未记录.
- Blame SAHChandler2 :). It's not documented yet, though.
1 :C ++ 11§5.1.2/19:
1: C++11 §5.1.2/19:
与 lambda-expression 关联的闭包类型具有已删除的(8.4.3)默认构造函数和已删除的副本分配运算符.
The closure type associated with a lambda-expression has a deleted (8.4.3) default constructor and a deleted copy assignment operator.
2 : http://llvm.org/viewvc/llvm-project?view=rev&revision=150620
这篇关于Objective-C ++ 11-为什么我们不能为lambda分配一个块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!