Fix a bug in ComPtr<T>.CopyTo when targeting same object

このコミットが含まれているのは:
Sergio Pedri committed 2023-10-08 17:11:36 +02:00
1 親 cfbfc2886b
コミット 9fbae2968e
1ファイル変更
+14 -4
+14 -4
ファイルの表示
@@ -52,13 +52,25 @@ internal unsafe struct ComPtr<T> : IDisposable
}
/// <summary>
/// Copies a given COM object into a target destination.
/// Copies a given COM object into a target destination, incrementing reference counts where needed.
/// </summary>
/// <param name="obj">The input COM object to copy.</param>
/// <param name="other">The target destination for the COM object.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void CopyTo(T* obj, ref T* other)
{
// We specifically need to increment the reference count on the source object before releasing the
// target object, to avoid issues in case source and destination were pointers to the same object
// (which can be the case even if the two pointers are not identical). To double check, a full check
// through an IUnknown* cast would be needed, but to avoid the extra QueryInterface call on both objects,
// we can just always do one AddRef call which avoids issues in all cases as well. The situation we need
// to avoid is that without a temporary copy, releasing the target object might actually destroy the
// object, causing the following AddRef call to AV.
if (obj is not null)
{
_ = ((IUnknown*)obj)->AddRef();
}
T* pointer = other;
if (pointer is not null)
@@ -66,13 +78,11 @@ internal unsafe struct ComPtr<T> : IDisposable
_ = ((IUnknown*)pointer)->Release();
}
_ = ((IUnknown*)obj)->AddRef();
other = obj;
}
/// <summary>
/// Writes a given COM object into a target (assumed uninitialized) destination.
/// Writes a given COM object into a target (assumed uninitialized) destination, incrementing reference counts where needed.
/// </summary>
/// <param name="obj">The input COM object to copy.</param>
/// <param name="other">The target destination for the COM object.</param>