From 6a71ee185b74a36d429ef8d918a73062c8b3c9fc Mon Sep 17 00:00:00 2001 From: David Machaj <46852402+dmachaj@users.noreply.github.com.> Date: Tue, 29 Oct 2024 15:33:40 -0700 Subject: [PATCH] Use a reference for the cast result to avoid a spurious addref/release --- cppwinrt/code_writers.h | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/cppwinrt/code_writers.h b/cppwinrt/code_writers.h index 9e329f551..78538af98 100644 --- a/cppwinrt/code_writers.h +++ b/cppwinrt/code_writers.h @@ -1129,9 +1129,13 @@ namespace cppwinrt if (is_remove_overload(method)) { // we intentionally ignore errors when unregistering event handlers to be consistent with event_revoker + // + // The `noexcept` versions will crash if check_cast_result throws but that is no different than previous + // behavior where it would not check the cast result and nullptr crash. At least the exception will terminate + // immediately while preserving the error code and local variables. format = R"( template auto consume_%::%(%) const noexcept {% - const auto castedResult = static_cast<% const&>(static_cast(*this)); + const auto& castedResult = static_cast<% const&>(static_cast(*this)); const auto abiType = *(abi_t<%>**)&castedResult; check_cast_result(abiType); abiType->%(%);% @@ -1142,7 +1146,7 @@ namespace cppwinrt { format = R"( template auto consume_%::%(%) const noexcept {% - const auto castedResult = static_cast<% const&>(static_cast(*this)); + const auto& castedResult = static_cast<% const&>(static_cast(*this)); const auto abiType = *(abi_t<%>**)&castedResult; check_cast_result(abiType); WINRT_VERIFY_(0, abiType->%(%));% @@ -1154,7 +1158,7 @@ namespace cppwinrt { format = R"( template auto consume_%::%(%) const {% - const auto castedResult = static_cast<% const&>(static_cast(*this)); + const auto& castedResult = static_cast<% const&>(static_cast(*this)); const auto abiType = *(abi_t<%>**)&castedResult; check_cast_result(abiType); check_hresult(abiType->%(%));%