Skip to content

Code Quality: Dispose unmanaged objects automatically using IDisposable #16071

@0x5bfa

Description

@0x5bfa

Description

I'd propose disposable structs in order to avoid memory leaks due to undisposed unmanaged objects.

The structs

  • ComPtr
  • ComHeapPtr

Usage

{
    try
    {
        using ComPtr<T1> pObj1 = default;
        var hr = CoCreateInstance(..., (void**)pObj1.GetAddressOf());
        var hr = pObj1.Get()->Method1(...);

        using ComHeapPtr<LPWSTR> pDisplayName = default;
    }
    catch (Exception ex)
    {
        // Log the exception
    }
}

Concerned code

  • All com related unmanaged objects.

Gains

  • prevent memory leaks

Requirements

  • Implement the structs that implements IDisposable and use it through 'using' statement

Comments

No response

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

Status

✅ Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions