C ++ 11ラムダで参照によってオブジェクトをキャプチャし、オブジェクトをスコープ外に出してからラムダを実行すると、オブジェクトにアクセスできます。次のコードを実行すると、デストラクタがすでに呼び出されていても、ラムダ呼び出しはオブジェクトにアクセスできます。なぜこれが機能するのか、なぜランタイムエラーが発生しないのかを誰かが説明できますか?
#include <iostream>
class MyClass {
public:
int health = 5;
MyClass() {std::cout << "MyClass created!\n";}
~MyClass() {std::cout << "MyClass destroyed!\n";}
};
int main(int argc, const char * argv[])
{
std::function<bool (int)> checkHealth;
if(true) {
MyClass myVanishingObject;
checkHealth = [&myVanishingObject] (int minimumHealth) -> bool {
std::cout << myVanishingObject.health << std::endl;
return myVanishingObject.health >= minimumHealth;
};
} // myVanishingObject goes out of scope
// let's do something with the callback to test if myVanishingObject still exists.
if(checkHealth(4)) {
std::cout << "has enough health\n";
} else {
std::cout << "doesn't have enough health\n";
}
return 0;
}
出力は次のとおりです。
MyClass created!
MyClass destroyed!
5
has enough health