I would like to use unique_ptr with my deleter. I would like my unique_ptr with my deleter to be fully compatible with unique_ptr with default deleter.
I did so:
template <typename T>
struct QObjectDeleteLaterDeletor :
public std::default_delete<T>
{
void operator()(T *p)
{
p->deleteLater();
}
};
template <typename T, class... Args>
std::unique_ptr<T> qtMakeUniqueSpecial(Args&&... args)
{
return std::unique_ptr<T>(
new T(std::forward<Args>(args)...),
QObjectDeleteLaterDeletor<T>());
}
This compiles, but does not work. My custom deleter ignored and default one used instead as if I did not specify it at all.
I need all of this to be possible to do things like that:
auto ptr1 = qtMakeUniqueSpecial<MyObject>();
std::unique_ptr<MyObject> ptr2;
ptr2 = std::move(ptr1);
Please note that now even ptr1.reset() will lead to calling the standard deleter, not my one.
Is it even possible?
You're trying to use
which has a second template argument
Deleter
. Failing to specify that, it defaults tostd::default_delete<T>
. Your codepasses a
const std::default_delete<T>&
to the constructor ofstd::unique_ptr<T>
, because that's what the constructor expects. Upon destruction (or call to memberreset()
), this will be called.Note that the behaviour of
std::shared_ptr
is different: there is no second template argument for the deleter, though a custom deleter may be provided at construction (this will need to be stored via type erasure, which is avoided withstd::unique_ptr
).