我明白捕捉this
在拉姆達(修改對象屬性)的正確方法如下:爲什麼我不能在lambda中捕獲這個通過引用('&this')?
auto f = [this]() { /* ... */ };
不過我很好奇,下面的特點我見過:
class C {
public:
void foo() {
// auto f = []() { // this not captured
auto f = [&]() { // why does this work?
// auto f = [&this]() { // Expected ',' before 'this'
// auto f = [this]() { // works as expected
x = 5;
};
f();
}
private:
int x;
};
,我迷茫了(並想回答)的古怪就是爲什麼以下工作:
auto f = [&]() { /* ... */ }; // capture everything by reference
爲什麼我不能明確上尉URE this
參考:
auto f = [&this]() { /* ... */ }; // a compiler error as seen above.
你爲什麼想要?對於指針的引用可能會被認爲有用的事物而言:「this」不能被改變,它不足以使得引用更快......並且**無論如何**,_it doesn'實際上是存在的,所以它沒有真正的生命週期,這意味着任何對它的引用都會被定義爲懸而未決的。 '這是一個價值,而不是一個左值。 – 2016-08-16 15:38:34