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:
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
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;
}