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?
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...
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With