Search code examples
c++boostlambdashared-ptrraii

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!


Solution

  • 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));