Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a custom deleter with a templateized QSharedPointer

I am trying to write a templatized wrapper to a class such that the wrapper can manage the lifespan using a shared pointer. (I can’t modify the class(es) that I’m wrapping)

I would like to write a custom deleter such that I can debug and validate that the objects are being release at the correct time.

#include <QtCore/QCoreApplication>
#include <QSharedPointer>

class A {
public:
    virtual ~A() {
        qInfo() << "Deleting an A";
}
    void doA(void) {
        qInfo() << "Doing A thing";
    }

};

class B : public A {

};

class SharedA {
public:
    QSharedPointer<A> m_spA;
};

//
//template<class T> void DeleteB(T* p) {
//    qInfo() << "deleting shared";
//    delete p;
//}


template<class T>
class SharedB :public SharedA {
public:
    static void DeleteB(T* p) {
        qInfo() << "deleting shared";
        delete p;
    }
    SharedB() {
        m_pB = new B;
        A* pA = dynamic_cast<A*>(m_pB);
        m_spA = QSharedPointer<A>(pA, DeleteB);
    }
    B* m_pB;
};


void lifespan() {
    SharedB<B> bThing;
    bThing.m_pB->doA();

}

int main(int argc, char* argv[])
{
    QCoreApplication a(argc, argv);

    lifespan();

}

Unfortunately I end up with the following syntax error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error   C2664   'void (T *)': cannot convert argument 1 from 'T *' to 'T *' testshared  Qt\6.4.1\msvc2019_64\include\QtCore\qsharedpointer_impl.h   79  

>Solution :

If you keep managing with QSharedPointer<A>,

static void DeleteB(T* p) {
    qInfo() << "deleting shared";
    delete p;
}

should be

static void DeleteB(A* a) {
    auto p = static_cast<T*>(a);
    qInfo() << "deleting shared";
    delete p;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading