mercredi 30 septembre 2020

passing a temporary lambda by const std::function reference should fail but seems to work

This is a simplified version of what I am doing:

#include <iostream>
#include <functional>

class thing
{
public:
    void register_fn(const std::function<void()> &fn)
    {
        m_fn = fn;
    }
    void run()
    {
        m_fn();
    }
    std::function<void()> m_fn;
};

int main() {

    // Create a thing object
    thing t;

    // In a limited scope
    {
        // Local lambda
        auto afn = []{std::cout << "hi\n";};
        // Store the lamda by reference
        t.register_fn(afn);
    }

    // Run the stored lambda (which should be destroyed - therefore dangling reference??)
    t.run();

    // Take a copy
    thing t2 = t;
    t2.run();

    return 0;
}

see it running here: https://godbolt.org/z/6qW3ro

So, I have a class that stores a temporary lambda passed by reference. The lamda afn's scope is limited so that once it is passed to the register function it goes out of scope. Then outside of this scope I call the run function which should be running the (dangling?) reference to the lambda.

This has been working, but recently looking back at my code I have a doubt. Since the lambda is temporary (done here by limiting the scope of my lambda object afn) - this should not work... I can't quite get my head around why it is working - unless by luck and this is undefined behaviour?

Or... what have I mis-understood here? - because that is probably the most likely explanation!

Aucun commentaire:

Enregistrer un commentaire