microsoft / cppwinrt

C++/WinRT
MIT License
1.64k stars 236 forks source link

Feature request: Allow delegates consisting of weak reference + lambda #1371

Closed oldnewthing closed 9 months ago

oldnewthing commented 9 months ago

Version

2.0.230706.1

Summary

We have found that a very common pattern for event handlers is to capture a weak reference into a lambda, and in the event handler, try to upgrade the weak reference to a strong one, and if so, do some work:

widget.Closed([weak = get_weak(), data](auto&& sender, auto&& args)
{
    if (auto strongThis = weak.get())
    {
        strongThis->do_all_the_things(data);
    }
});

We propose extending the existing delegate constructors to permit a winrt::weak_ref + lambda (or std::weak_ptr + lambda), which simplifies the above to

widget.Closed({ get_weak(), [this, data](auto&& sender, auto&& args)
{
    do_all_the_things(data);
} });

Reproducible example

No response

Expected behavior

No response

Actual behavior

No response

Additional comments

No response