Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unique_ptr and QObject::deleteLater

Tags:

c++11

qt

I would like my std::unique_ptr to call QObject::deleteLater to destruct the object.

I can't figure out how to do it.

Nothing I tried compiles.

E.g.

std::unique_ptr<SomeQObject, decltype(&QObject::deleteLater)> var(
                pointer, &QObject::deleteLater);

Please help...

Addition #1.

OK, I've found that this works:

std::unique_ptr<QObject, decltype(std::mem_fun(&QObject::deleteLater))> var(
            pointer,
            std::mem_fun(&QObject::deleteLater));

Instead of this one:

std::unique_ptr<QObject, decltype(&QObject::deleteLater)> var(
            pointer,
            QObject::deleteLater);

But it's too ugly for me to use it. Is there a good way?

like image 480
Alexander Dyagilev Avatar asked Dec 30 '16 20:12

Alexander Dyagilev


2 Answers

It's very very simple and straightforward, by the way.

struct QObjectDeleteLater {
    void operator()(QObject *o) {
        o->deleteLater();
    }
};

template<typename T>
using qobject_delete_later_unique_ptr = std::unique_ptr<T, QObjectDeleteLater>;

Usage:

qobject_delete_later_unique_ptr<QObject> ptr(new QFooBar);

Bonus points if you can come up with a sensible name...

like image 187
peppe Avatar answered Nov 23 '22 21:11

peppe


As doc says it :

Type requirements

-Deleter must be FunctionObject or lvalue reference to a FunctionObject or lvalue reference to function, callable with an argument of type unique_ptr::pointer

You are 'stuck' here with std::bind, std::mem_fun or lambda, you can't just use member func pointer in this context because its not satisfying requirements


lambda version:

  auto deleter = [](QObject* obj) {obj->deleteLater();};
  std::unique_ptr<QObject, decltype(deleter)> x(new QObject(), deleter);
like image 20
Oleg Bogdanov Avatar answered Nov 23 '22 20:11

Oleg Bogdanov