Resource leak when using ComPtr with std::vector

Raghunandan 0 Reputation points
2023-01-20T09:11:25.9033333+00:00

I have the following simple code which creates 10 resources and stores them in ComPtr. But at the end of the program, debugger reports resource leaks. Is it valid to use CompPtr in std::vector

#include <iostream>
#include <vector>
#include <dxgi.h>
#include <dxgi1_3.h>
#include <d3d12.h>
#include <wrl.h>
#include <dxgidebug.h>

int main()
{
        Microsoft::WRL::ComPtr<IDXGIFactory1> pFactory;
        Microsoft::WRL::ComPtr<IDXGIAdapter> pAdapter

        CreateDXGIFactory1(IID_PPV_ARGS(&pFactory));
        pFactory->EnumAdapters(0, &pAdapter);

        Microsoft::WRL::ComPtr<ID3D12Device> pDevice;
        D3D12CreateDevice(pAdapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&pDevice));

        D3D12_HEAP_PROPERTIES heapProps = {};
        D3D12_RESOURCE_DESC desc = {};
        heapProps.Type = D3D12_HEAP_TYPE_DEFAULT;

        desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
        desc.Width = 1920;
        desc.Height = 1080;
        desc.DepthOrArraySize = 1;
        desc.MipLevels = 1;
        desc.Format = DXGI_FORMAT_R8_UNORM;
        desc.SampleDesc.Count = 1;
        desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
        
        std::vector<Microsoft::WRL::ComPtr<ID3D12Resource>> resourceList;
        for (int i = 0; i < 10; i++)
        {
            ID3D12Resource* pResource;
            pDevice->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE,
                &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
                IID_PPV_ARGS(&pResource));
            resourceList.emplace_back(pResource);
        }
        /*
        Microsoft::WRL::ComPtr<ID3D12Resource> pResource;
        pDevice->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE,
            &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
            IID_PPV_ARGS(pResource.GetAddressOf()));*/


	return 0;
}
Developer technologies C++
{count} votes

2 answers

Sort by: Most helpful
  1. David Lowndes 4,726 Reputation points
    2023-01-20T11:04:51.5333333+00:00

    How about if you change:

    ID3D12Resource* pResource;

    to be a CComPtr as you have elsewhere?

    4 people found this answer helpful.
    0 comments No comments

  2. Raghunandan 0 Reputation points
    2023-01-20T10:27:38.62+00:00

    Thanks. This is working.

    It looks assigning a raw pointer to ComPtr resulting in the leak.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.