Lambda Capture and Memory Management

When I take an object by reference in a C ++ 11 lambda, let the object go out of scope and then execute the lambda, it still has access to the object. When I execute the following code, the lambda call can access the object, although the destructor has already been called! Can someone explain why this works and why I am not getting a runtime error?

#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 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;
}

Here's the conclusion:

MyClass created!
MyClass destroyed!
5
has enough health
+5
source share
1 answer

According to cppreference.com documentation for lambda functions

Dangling links

, , , , undefined. ++ .

, , , , , lambda undefined. UB - " , ", , undefined, , .

, , . , , main , . , , 5 , , .

, !

+17

All Articles