Skip to content

Allow std::string_view like behaviour for temporary lambda captures #12

@duckdoom5

Description

@duckdoom5

Hi I was trying out this library but I ran into a problem.
Maybe it's just me not understanding the intended use case or maybe there's something else going wrong.

I tried to use std::function_ref as a drop-in replacement for parameters that used to be template args.
The code below shows a simplified version of what I attempted to do:

namespace {
    class CallbackStore {
    public:
        using CallbackSig = void(int);

        void AddCallback(const std23::function_ref<CallbackSig>& action) {
            _actions.emplace_back(action);
        }

        void Invoke(int args) const {
            for (const std23::function<CallbackSig>& f : _actions)
                f(args);
        }

    private:
        std::vector<std23::function<CallbackSig>> _actions;
    };

    CallbackStore g_store;
} // namespace

AppMain::AppMain() {
    g_store.AddCallback([&](int i) {
        OnCallback(i);
    });
}

void AppMain::OnInitialize() {
    g_store.AddCallback([&](int i) {
        OnCallback(i);
    });
    g_store.Invoke(2);
}

void AppMain::OnCallback(int i) {
    std::cout << std::format("Callback value: {}\n", i);
}

This isn't a 100% replicate-able example, but I hope it does suffice.

So the issue is that the first callback in the AppMain() constructor has a 'corrupted' this pointer.
(Note: I placed a breakpoint before the callback was added to capture the address of the AppMain class to display that it has not moved)
image

The second callback works fine.
image

If I understand lambdas correctly, I assume what happens here is that the compiler generated lambda captured data storage is deleted before the callback is invoked. Is this just a bug or is the way I implemented it simply incorrect?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions