View Full Version : Custom Deleter for QSharedPointer

8th May 2013, 17:45
UPD: It all works as expected, sorry for my mistake. Please, delete or close this topic.

Hi, all!

How to specify custom Deleter for QSharedPointer correctly?

class A
void f() {...}

QSharedPointer<A> pA1(new A, ???);

What shall I write instead of ??? in a code above to make QSharedPointer call method f() of object that is about to be deleted? Or it is not possible at all?
I.e. i want pA1 to call method f() of controlled instance of class A when pA1's reference counter drops to 0. &A::f doesn't seem to work since A::f() is not static and object must be specified.

But why does the code below always work when A is subclass of QObject?

QSharedPointer<A> pA2(new A, &QObject::deleteLater);

Non-static deleteLater() method of newly created class A instance is called as ref. counter of pA2 drops to 0.

Thank you in advance && Sorry for my English

P.S. I use GCC version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5), Qt 4.8.4

9th May 2013, 01:53
QSharedPointer<A> pA1(new A, &A::f);

This is a working example showing it calls the method with the correct this pointer:

#include <QtCore>

class Test
Test() { qDebug() << "Constructed" << this; }
~Test() { qDebug() << "Destroyed" << this; }
void deleteThis() {
qDebug() << "Do this" << this;
// perform elaborate deletion ritual
delete this;

int main(int argc, char **argv)
QCoreApplication app(argc, argv);
QSharedPointer<Test> test1(new Test, &Test::deleteThis);
QSharedPointer<Test> test2(new Test, &Test::deleteThis);
QSharedPointer<Test> test3(test1);
test1.clear(); // no deletion, kept alive by test3
return 0;

Edit: Hmm, how did I miss the update?

8th February 2017, 17:06
Have a question though. is it true that, custom deleter is copied in QSharedPoointer operator =?

10th February 2017, 19:14
Have a question though. is it true that, custom deleter is copied in QSharedPoointer operator =?

You could easily modify ChrisW67's code to add a line that assigns test2 = test1 for example and verify that it does.