Qt::MakePointer for creating QPointer as std::make_shared for creating std::shared_ptr



  • In modern C++ there is almost no need to use raw new and delete. As Bjarne Stroustrup is saying in his "A Tour of C++": "Avoid ‘‘naked’’ new and delete operations; §4.2.2.". We use standard containers and smart pointers for that, with std::make_shared and std::make_unique functions for smart pointers creation.

    In Qt we also have QSharedPointer and QSharedPointer<T>::create(...) method. But we don't use smart pointers in Qt much, due to parent-driven memory model. And most of QObjects are created with raw new operations. Maybe it is a proper thing to add some C++14-style wrapper for creating QObjects like this:

    @
    namespace Qt
    {
    template<class T, class... Args>
    QPointer<T> MakePointer(Args&&... args)
    {
    T* pObject = new T(std::forward<Args>(args)...);
    Q_ASSERT(pObject->parent() != nullptr);
    return pObject;
    }
    }
    @

    Now, one can safely call Qt::MakePointer to create a QObject and be sure it will not leak due to an assertion for an existing parent. And it will free all the calling code from raw new operations. One can always use raw delete to destroy the object, but he does not have to. And even if he will, it will not lead to dangling pointers problem since QPointer is automatically set to null in this case.

    I'm planning to use this approach in my code. Do you think it is relevant? Are there any drawbacks?


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    For this kind of design question, you should rather post to the interest mailing list, you'll find there Qt's developers/maintainers. This forum is more user oriented.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.