Making an agile version of a Windows Runtime delegate in C++/WinRT, part 8
cppdashboard.dev/r/2026/08/making-an-agile-version-of-a-windows-runtime-delegate-in-cpp-3This article discusses handling exceptions in the context of C++/WinRT delegates, particularly focusing on the construction order of lambda captures and potential reference leaks. It emphasizes the importance of precreating deleters to avoid issues with raw pointers.
From the article
Last time, we fixed the problem of an exception thrown from the custom deleter’s constructor resulting in a reference leak . But wait, there’s another source of exceptions.
if (d.try_as<::INoMarshal>()) { in_context_deleter del; void* p; if constexpr (std::is_reference_v<Delegate>) { p = winrt::detach_abi(d); } else { winrt::copy_to_abi(d, p); } return [p = std::unique_ptr<void, in_context_deleter>(p, std::move(del)), token = get_context_token()](auto&&...args) { if (token == get_context_token()) { std::remove_reference_t<Delegate> d; winrt::copy_from_abi(d, p.get()); d(std::forward<decltype(args)>(args)...); } else { throw winrt::hresult_error(CO_E_NOT_SUPPORTED); } }; } Precreating the deleter means that an exception in its construction happens before we do any funny business with the…
Share this resource