在此 DX12 代码中使用 GetAddressOf 和 & 有什么区别?

问题描述 投票:0回答:1

我有以下来自 Frank Luna 的 DX12 书中的代码:

D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
ThrowIfFailed(md3dDevice->CreateCommandQueue(
    &queueDesc, IID_PPV_ARGS(&mCommandQueue)));
ThrowIfFailed(md3dDevice->CreateCommandAllocator(
    D3D12_COMMAND_LIST_TYPE_DIRECT,
    IID_PPV_ARGS(mDirectCmdListAlloc.GetAddressOf())));
ThrowIfFailed(md3dDevice->CreateCommandList(
    0,
    D3D12_COMMAND_LIST_TYPE_DIRECT,
    mDirectCmdListAlloc.Get(), // Associated command allocator
    nullptr, // Initial PipelineStateObject
    IID_PPV_ARGS(mCommandList.GetAddressOf())));
// Start off in a closed state. This is because the first time we
// refer to the command list we will Reset it, and it needs to be
// closed before calling Reset.
mCommandList->Close();

我想知道的是,为什么他在传递队列

&
时使用
ComPtr
运算符,而在其他两个时使用
GetAddressOf
方法?

com directx directx-12 wrl
1个回答
0
投票

使用

Microsoft::WRL::ComPtr
我更喜欢使用
ReleaseAndGetAddressOf
GetAddressOf
而不是使用
operator&
重载。这有几个原因。

旧版 ATL CComPtr 在使用

operator&
时相当于
GetAdddressOf
,并带有一个断言来假设它是 nullptr。 WRL ComPtr 使用
ReleaseAndGetAddressOf
这是 更安全 默认值,以避免潜在的资源泄漏,但当您在意想不到的情况下最终得到“nullptr”结果(例如尝试传递指针)时,也可能会导致混乱 - Direct3D API 中经常使用到指针。

在上面 Luna 的代码片段中,使用 .ReleaseAndGetAddressOf 是一个

更安全
的选择,因为被调用的方法是一个创建函数,并且成员变量可能已经被设置。即使该类被“误用”,这也可以避免内存泄漏。如果我要初始化一个我知道刚刚创建的局部变量,因此它始终为 nullptr,我更喜欢使用
.GetAddressOf

请参阅此维基页面以获取更多建议。

© www.soinside.com 2019 - 2024. All rights reserved.