【问题标题】:using a custom deleter for std::shared_ptr on a direct3d11 object在 direct3d11 对象上为 std::shared_ptr 使用自定义删除器
【发布时间】:2012-11-17 23:54:27
【问题描述】:

当我使用 std::shared_ptr 并需要自定义删除器时,我通常会创建对象的成员函数以促进它的破坏,如下所示:

class Example
{
public:
    Destroy();
};

然后当我使用共享 ptr 时,我就是这样:

std::shared_ptr<Example> ptr(new Example, std::mem_fun(&Example::Destroy));

问题是,现在我正在使用 d3d11,我想使用 com 发布函数作为 std::shared_ptr 自定义删除器,像这样

std::shared_ptr<ID3D11Device> ptr(nullptr, std::mem_fun(&ID3D11Device::Release));

但我收到此错误:

error C2784: 'std::const_mem_fun1_t<_Result,_Ty,_Arg> std::mem_fun(_Result (__thiscall _Ty::* )(_Arg) const)' : could not deduce template argument for '_Result (__thiscall _Ty::* )(_Arg) const' from 'ULONG (__stdcall IUnknown::* )(void)'

然后当我像这样明确指定模板参数时:

std::shared_ptr<ID3D11Device> ptr(nullptr, std::mem_fun<ULONG, ID3D11Device>(&ID3D11Device::Release));

我收到此错误,

error C2665: 'std::mem_fun' : none of the 2 overloads could convert all the argument types

谁能解释一下为什么我不能用这个函数作为删除器?

注意:不建议我使用 CComPtr,我使用的是 msvc++ express edition :\

【问题讨论】:

  • 你能用std::mem_fn代替std::mem_fun吗?
  • std::mem_fun 已弃用,请使用 std::mem_fn
  • 使用 lambdas 或 std::bind,这样更容易理解。
  • 试试static_cast&lt;ULONG (ID3D11Device::*)(void)&gt; (&amp;ID3D11Device::Release)

标签: c++ c++11 directx-11


【解决方案1】:

试试这个

struct Releaser{
    void operator()(ID3D11Device* p){
        p->Release();

    };

};


std::shared_ptr<ID3D11Device> ptr(nullptr, Releaser());

【讨论】:

    【解决方案2】:

    这个怎么样?

    std::shared_ptr<ID3D11Device> ptr(nullptr, [](ID3D11Device* ptr){ptr->Release();} ); 
    

    【讨论】:

    • 工作正常,但有 2 个问题。 1)为什么在用nullptr构造时它仍然调用删除器。 2)那个lambda的返回类型是什么?我对他们有点陌生:\
    • @FatalCathasis : 这个 lambda 的返回类型是 void。
    • @ildjarn :等等,不是 lambda 的返回类型。对不起,我的意思是 lambda 本身是什么类型?
    • @FatalCatharsis : Lambda 具有匿名(不可命名)类型,每个类型都是唯一的并由编译器生成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 2014-08-27
    • 2012-09-02
    相关资源
    最近更新 更多