Uh oh!
There was an error while loading. Please reload this page.
Add [[nodiscard]] to overloads of static events that return winrt::event_token - #1559
Conversation
Charles Milette (sylveon)
commented
Apr 5, 2026
Users may want to permanently subscribe to an event for the lifetime of their program, in which case discarding the event token seems intentional. |
It does not affect non-static events, and their overloads that return winrt::event_token still do not have this attribute. Non-static events can be released through the object they are associated with, so discarding the return value does not cause a leak, whereas static events do not have such an object. The impact of this patch is very small; if users wish to discard the return value, they can use (void)expr. |
Charles Milette (sylveon)
commented
Apr 5, 2026
I think we should only add [[nodiscard]] if dropping the value is always considered an error |
Yexuan Xiao (YexuanXiao)
commented
Apr 5, 2026
I'm not entirely sure which static events might need to be subscribed to permanently, but at least the Clipboard example performs proper cleanup and I don't believe that well-written code should allow such a leak. |
There was a problem hiding this comment.
Pull request overview
This PR updates the C++/WinRT code generator to annotate static event “add” overloads (the ones that return winrt::event_token) with [[nodiscard]], helping prevent accidental loss of the token needed to later unsubscribe from static events (where losing the token effectively leaks the handler).
Changes:
- Treat
add_overloads in static factory method generation as “events” and apply[[nodiscard]]to their generated static declarations. - Minor refactor to compute
is_eventonce and reuse it for both declaration emission and revoker-type emission logic.
Some events in WinRT are static, such as Clipboard.ContentChanged.For these events, the only way to release a delegate is through
winrt::event_token, because the delegate is not stored in any user-controllable object. Therefore, if thewinrt::event_tokenreturned by these events is discarded, the delegate will leak. This PR adds the[[nodiscard]]attribute to the overloads that returnwinrt::event_tokenfor static events to indicate that their return value should not be ignored, just like the overloads that return a revoker.