如何修复“&需要左值”

How can I fix "& requires l-value"

所以,我创建了一个项目并在其中复制了this tutorial。当我尝试 运行 它时,它给了我这个错误: C2102 & requires l-value at

m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_frameIndex].Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET));

我搜索了很多,但没有找到符合上下文的内容。我能做些什么来修复它?

这与 Issue #652 Error building D3D12MeshShaders (on VS 16.8.0 Preview 3.0) in the DirectX-Graphics-Samples 存储库下报告的构建错误基本相同。

I'm getting error C2102: '&' requires l-value on many of the lines. Usually it's when a CD3DX12 constructor is directly used with an &, for example [...]

问题仍未解决,评论中给出了临时解决方法:

The use of an address of an r-value like this [...] is non-conforming code.

Visual C++ emits a warning C4238 here with /W4 warning level 4, but most VC projects default to level 3 including these samples. [...] Looks like the latest Visual C++ updates for /permissive- have upgraded this to an error.

You can work around this issue for now by disabling /permissive- by changing "Conformance Mode" to "No" in the C/C++ -> Language project settings.

问题是您试图获取并传递右值(特别是纯右值)的地址。

虽然从生命周期的角度来看这很好(没有引用或指向右值的指针转义完整语句在这种情况下),语言不知道也不会尝试找出来。

我建议您将 keep() 添加到 std::move():

template <class T>
constexpr auto& keep(T&& x) noexcept {
    return x;
}

像这样使用:

m_commandList->ResourceBarrier(1,
    &keep(CD3DX12_RESOURCE_BARRIER::Transition(m_renderTargets[m_frameIndex].Get()),
    D3D12_RESOURCE_STATE_PRESENT,
    D3D12_RESOURCE_STATE_RENDER_TARGET));

请记住,你是在违背常理,因此任何误用都是你自己的错。