[Interest] What's the recommended way to put QObjects in smart pointers?

Nikos Chantziaras realnc at gmail.com
Thu May 5 17:14:21 CEST 2016


Well, lots of strong opinions on this one :-)

Anyway, to each his own. Of course I know that C++ isn't Java, nor would 
I want it to be. But just because C++ isn't Java doesn't mean I am in 
favor of poor exception safety or lots of manual checking and cleaning 
up. Yes, we still have to do these things, but the less of them we have 
to do, the better.

So for my own needs, I just came up with this:

template <class T, typename... Args>
auto q_make_unique(Args&&... args)
{
     auto tmp = std::make_unique<T>(std::forward<Args>(args)...);
     auto deleter = [q_ptr = QPointer<T>(tmp.get())](const T* obj)
     {
         if (q_ptr) {
             delete obj;
         }
     };
     std::unique_ptr<T, decltype(deleter)>
         uptr(tmp.release(), std::move(deleter));
     return uptr;
}

Which probably can be done better with less overhead, but I'll settle 
for "good enough" for now.


On 04/05/16 17:48, Nikos Chantziaras wrote:
> I've been removing every trance of 'new' and 'delete' from my code and
> switching to something like:
>
>    auto obj = std::make_unique<Type>(ctor args);
>
> (Or std::make_shared, depending on the situation.)
>
> But for QObjects with a parent, that can go horribly wrong. So I have to
> do annoying stuff like:
>
>    auto dialog = new QDialog(parent);
>    // work...
>    delete dialog;
>
> Yes, 'parent' will eventually delete 'dialog', but that doesn't help
> much when 'parent' is a long lived object (like the main application
> window.)
>
> Is there a Qt-specific idiom where I can manage QObjects that have a
> parent with a smart pointer and not have to worry about double-deletion?
>
> Or, to phrase it in another way, is there a way to eliminate the 'new'
> keyword completely from my code-base when using QObjects with a parent?
>





More information about the Interest mailing list