[Development] parented_ptr
Daniel Schürmann
daschuer at mixxx.org
Mon Nov 3 19:12:57 CET 2025
On Mon, Nov 3, 2025 at 4:59 PM Ville Voutilainen <
ville.voutilainen at gmail.com> wrote:
> On Mon, 3 Nov 2025 at 17:52, Ville Voutilainen
> <ville.voutilainen at gmail.com> wrote:
> > > the workaround is the rather ugly:
> > >
> > > parent.createChild<QObject>(&parent);
> >
> > That's not needed at all.
>
> See, the reason is that QObject parents aren't of type
> SomeTypeInheritingQObject. They are QObjects.
>
> That's why we don't need to deduce the parent type (which we can do
> since C++23, but we don't need to go to that here),
> and QObject works for the parent type.
>
> Same goes for QWidgets.
>
> You can of course pass whatever derived type pointer as the parent
> argument, it will just get implicitly converted to a pointer
> to the base type.
QObject does not work as an universal parent type. This works only for
lifetime management.
There are a couple of overloads for setParent that require a different type
to tie some other ends.
Adding a function that takes an unexpected overload of a base class is a
source of headaches.
A Quick search reveals ~10 different overloads in qtbase alone like:
void QWindow::setParent(QWindow *parent)
This implementation will cover all of them:
template <class T, class X>
QParentedPointer<T> qAddChild(X *parent, std::unique_ptr<T> child)
{
Q_ASSERT(child && parent);
child->setParent(parent);
return QParentedPointer<T>(child);
}
Thank you for the hint that this pointer deducing is a C++23 feature. Now I
have found it we can do:
class QObject {
public:
template <typename Self, typename T>
QParentedPointer<T> addChild(this Self&& self, std::unique_ptr<T> child)
{
Q_ASSERT(child);
child->setParent(&self);
return QParentedPointer<T>(std::move(child));
}
}
This works for all of them (not tested)
Do you see a chance to add that with a C++23 guard?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20251103/dbccf811/attachment-0001.htm>
More information about the Development
mailing list