Making an agile version of a Windows Runtime delegate in C++/WinRT, part 4
cppdashboard.dev/r/2026/08/making-an-agile-version-of-a-windows-runtime-delegate-in-cpp-7This 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 AddRef , and then we have to explicitly Release it.
Share this resource