当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - How to pass a deleter to a method in the same class that is held by a shared_ptr

问题描述:

I have several classes from 3rd party library similar to the class, StagingConfigDatabase, which requires to be destroyed after it is created. I am using a shared_ptr for RAII but would prefer to create the shared_ptr using a single line of code rather than using a seperate template functor as my example shows. Perhaps using lambdas? or bind?

struct StagingConfigDatabase

{

static StagingConfigDatabase* create();

void destroy();

};

template<class T>

struct RfaDestroyer

{

void operator()(T* t)

{

if(t) t->destroy();

}

};

int main()

{

shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), RfaDestroyer<StagingConfigDatabase>());

return 1;

}

I was considering something like:

shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), [](StagingConfigDatabase* sdb) { sdb->destroy(); } );

but that doesn't compile :(

Help!

网友答案:

I'll assume that create is static in StagingConfigDatabase because your initial code wouldn't compile without it. Regarding destruction, you can use a simple std::mem_fun :

#include <memory>

boost::shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), std::mem_fun(&StagingConfigDatabase::destroy));
网友答案:

What compiler are you using? Does it support C++0x features like lambdas? The following (which is basically the same as your example) compiles and works fine for me under MSVC 2010:

#include <iostream>
#include <memory>

struct X
{
    static X *create()
    {
        std::cout << "X::create\n";
        return new X;
    }

    void destroy()
    {
        std::cout << "X::destroy\n";
        delete this;
    }
};

int main()
{
    auto p = std::shared_ptr<X>(X::create(), [](X *p) { p->destroy(); });
    return 0;
}

By "works fine", I mean "outputs X::create followed by X::destroy".

分享给朋友:
您可能感兴趣的文章:
随机阅读: