Specifying a Deleter for std :: shared_ptr, which works on all objects of a particular type or its derived types

I have the following classes in my project

class Base
{
    public:
    virtual ~Base(){};
}

class Der1: public Base
{
    public:
    virtual ~Der1(){};
}

class Der2: public Base
{
    public:
    virtual ~Der2(){};
}

I hold the objects of these classes as std::shared_ptr. I need to provide a custom delete file for all objects that are of type Baseor any of it derived types.

The code I want in the deleter method will do the same for this whole object, say

class Deleter
{
    public:
    void operator()( Base * b )
    {
        //Do something
        delete b;
    }
}

Instead of providing deletion when constructing each object, such as

std::shared_ptr< Der1 > pDer1( new Der1(), Deleter() );
std::shared_ptr< Der2 > pDer2( new Der2(), Deleter() );

Is there a way to specify something like "for all common pointers to objects of type Base or its derived types to use Deleterfor deletion? Since the deleter class is just used in the shared_ptr constructor, how can someone specify a debiter for a certain type?

+4
1

create/ factory Base, shared_ptr . - :

class Base
{
  //...public...
  template <class Derived>
  static std::shared_ptr<Base> create()
  {
    return std::shared_ptr<Base>(new Derived, Deleter());
  }
};

EDIT: ...

, .

EDIT:

( , ):

#include <iostream>
#include <memory>

struct Base;

struct Deleter
{
    void operator()(Base* b);
};

struct Base
{
  //...public...
  template <class Derived, class ... Args>
  static std::shared_ptr<Base> create(Args&&... args)
  {
    return std::shared_ptr<Base>(new Derived(std::forward<Args>(args)...), Deleter());
  }
  virtual ~Base(){}
};

void Deleter::operator()(Base* b){ delete b; }


struct Derived : Base
{
  Derived(int a, int b, int c)
  {
  }
};

int main() {
    std::shared_ptr<Base> p = Base::create<Derived>(1,2,3);
    return 0;
}
+7

All Articles