mercredi 27 mai 2015

Specifying a Deleter for std::shared_ptr that works on all objects of a particular type or it's derived types

I have a 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 am holding the objects of these classes as std::shared_ptr. I need to provide a custom deleter for all the that are either of type Base or any of its derived types.

The code I want in the deleter method will be doing the same thing for all these object, say

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

Instead of providing the deleter during the construction of each objects like

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 the shared pointers to objects of type Base or it's derived types use "Deleter" for deletion? As deleter class is just taken in the constructor of shared_ptr how can someoone specify a deleter for a particular type?

Aucun commentaire:

Enregistrer un commentaire