How to pass a deleter to a method in the same class as shared_ptr

I have several classes from a third-party library similar to the StagingConfigDatabase class, which requires destruction after it is created. I use shared_ptr for RAII, but would prefer to create shared_ptr using a single line of code , instead of using a separate template functor, as my example shows. Perhaps using lambda? 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 considered something like:

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

but this will not compile :(

Help!

+3
source share
2 answers

, create StagingConfigDatabase, . , std::mem_fun:

#include <memory>

boost::shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), std::mem_fun(&StagingConfigDatabase::destroy));
+4

? ++ 0x, lambdas? ( , ) 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;
}

" ", " X:: create, X:: destroy".

+3

Source: https://habr.com/ru/post/1781271/


All Articles