3

我有几个来自 3rd 方库的类,类似于 StagingConfigDatabase 类,它需要在创建后被销毁。我正在为 RAII 使用 shared_ptr,但我更愿意使用一行代码创建 shared_ptr,而不是像我的示例所示那样使用单独的模板仿函数。也许使用 lambdas?或绑定?

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;
    }

我正在考虑类似的事情:

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

但这不编译:(

帮助!

4

2 回答 2

4

我假设这create是静态的,StagingConfigDatabase因为没有它您的初始代码将无法编译。关于销毁,您可以使用简单的std::mem_fun

#include <memory>

boost::shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), std::mem_fun(&StagingConfigDatabase::destroy));
于 2010-12-20T16:45:06.550 回答
3

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".

于 2010-12-20T16:41:34.387 回答