mardi 12 février 2019

From my understanding this lambda call should be invalid, but it does not crash. Why?

I am having trouble understanding why the following code does not crash.

class MyClass
{
public:
    MyClass() {    m_contents = 0xF0F0F0F0; }
    void Hello() { printf("Hello, address: %llx, contents: %x, size: %d\n", (long long int)this, m_contents, sizeof(MyClass)); }
    int m_contents;
};

int main()
{
    MyClass* MyObj = new MyClass();
    MyObj->Hello();

    auto MyLambda = [MyObj]()
    {
        if (MyObj != nullptr)
        {
            MyObj->Hello();
        }
    };

    memset(MyObj, 0, sizeof(MyClass));
    MyObj->Hello();
    delete MyObj;
    MyObj = nullptr;

    MyLambda();

    return 0;
}

This is the output:

Hello, address: 1ddb4a16100, contents: f0f0f0f0, size: 4
Hello, address: 1ddb4a16100, contents: 0, size: 4
Hello, address: 1ddb4a16100, contents: dddddddd, size: 4

I would have expected the lambda call to crash because I wiped out all the memory that it is using to call the Hello() function. I know the contents are wiped because m_contents becomes 0. After calling delete, m_contents becomes a random value, but still, Hello() is called and there is no crash.

Follow up question: In a lambda where I pass this as a capture, is there a chance that this becomes null or invalid by the time the lambda is called?

Aucun commentaire:

Enregistrer un commentaire