Article

Making an agile version of a Windows Runtime delegate in C++/WinRT, part 4

The Old New Thing ·The Old New Thing ·Published 2026-07-23 ·5 min read

This article discusses optimizing a wrapper delegate in C++/WinRT by using context tokens for faster checks instead of comparing COM objects. It highlights the importance of keeping the context alive for accurate comparisons.

From the article

Last time, we wrote a wrapper delegate that checked whether the context it was being invoked from matched the context it was captured from .

if (d.try_as<::INoMarshal>()) { return [d = std::forward<Delegate>(d), context = winrt::capture<IContextCallback>(CoGetObjectContext)](auto&&...args) { if (context == winrt::capture<IContextCallback>(CoGetObjectContext)) { d(std::forward<decltype(args)>(args)...); } else { throw winrt::hresult_error(CO_E_NOT_SUPPORTED); } }; } We did this by comparing context objects.

This obtains the current object context in order to compare it with the original one, and that means an internal Add­Ref , and then we have to explicitly Release it.


Share this resource


Discovered 2026-08-02 Source The Old New Thing Archive 2026-08 →