[Interest] Qt::MakePointer for creating QPointer as std::make_shared for creating std::shared_ptr

Mikhail Matrosov mikhail.matrosov at gmail.com
Wed Oct 15 23:56:46 CEST 2014


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:

   1. namespace Qt <http://qt-project.org/doc/Qt.html>
   2. {
   3.   template<class T, class... Args>
   4.   QPointer <http://qt-project.org/doc/QPointer.html><T> MakePointer(
   Args&&... args)
   5.   {
   6.     T* pObject = new T(std::forward<Args>(args)...);
   7.     Q_ASSERT(pObject->parent() != nullptr);
   8.     return pObject;
   9.   }
   10. }

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?

PS This is a cross-post of my question from Qt forums:
http://qt-project.org/forums/viewthread/48541, where SGaist
<http://qt-project.org/mebmer/39728> suggested me to post here.

Best regards, Mikhail Matrosov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20141016/84bc309e/attachment.html>

More information about the Interest mailing list