Closed Nwpuer closed 9 years ago
大家不用管原题是什么了,原题比较长,只要帮我解释一下可以这样做吗?这样做的效果是什么?为什么捕获alloc不行?谢谢大家了~
@Nwpuer
不可以这么做。
alloc
实际是 this->alloc
,其作用域属于 this
麾下,直接去捕获 alloc
会捕获不到。this
,可以用 [&]
或 [=]
,但这样都不如 [this]
表达精准。C++ 标准 (Section 5.1.2 p10 of the ISO C++11 specification):
The identifiers in a capture-list are looked up using the usual rules for unqualified name lookup (3.4.1); each such lookup shall find a variable with automatic storage duration declared in the reaching scope of the local lambda expression. An entity (i.e. a variable or this) is said to be explicitly captured if it appears in the lambda-expression’s capture-list.
其中 a variable with automatic storage duration 就是中文社区经常说的“存在栈上”,而 class member 是“存在堆上”的, lambda 表达式可直接捕获前者,后者需要借助 this 指针。
是否可以理解为捕获了this才能使用this作用域内的成员?而且只要捕获this就能使用this作用域内所有成员,无需显式指定,比如this->alloc?
@Nwpuer 可以这么理解。
@pezy Thank you!
@Nwpuer
For such topic, I mean variable scope, no c++ book is good reference. Currently, I suggest just try to remember things like @pezy said. However, if you want to dive in, I recommend to go through a decent compiler tutorial, say dragon book, in which you want to look at the symbol table part and figure out what data structure is often used to implement it. After that, it's quite straitforward to understand why this
is needed to capture.
@Mooophy 我也是觉得我目前记住这个就好了,因为还是有一点不明白。谢谢啦!
问题来源于C++Primer :Exercise 13.43: for_each(elements, first_free, [this](std::string &rhs){ alloc.destroy(&rhs); }); 我感到有点疑问。为什么不是捕获alloc,而是捕获this呢?