microsoft / cppwinrt

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

How does `winrt::auto_revoke` not result in memory leaks? #1428

Closed amtopel closed 1 month ago

amtopel commented 1 month ago

Version

No response

Summary

This isn't a bug. Just a question. According to the docs, an auto event revoker will revoke when it goes out of scope. The docs provide this example:

struct Example : ExampleT<Example>
{
    Example(winrt::Windows::UI::Xaml::Controls::Button button)
    {
        m_event_revoker = button.Click(
            winrt::auto_revoke,
            [this](IInspectable const& /* sender */,
            RoutedEventArgs const& /* args */)
        {
            // ...
        });
    }

private:
    winrt::Windows::UI::Xaml::Controls::Button::Click_revoker m_event_revoker;
};

But in this case m_event_revoker won't go out of scope until the class is deleted. The class won't be deleted until all references go to zero. And references won't go to zero until the event handler has been revoked. So shouldn't this result in a circular reference and memory leak? Or maybe I'm missing something.

Reproducible example

No response

Expected behavior

No response

Actual behavior

No response

Additional comments

No response

sylveon commented 1 month ago

There is no strong reference in this case, this in the lambda capture is a raw pointer.