[Development] parented_ptr
Daniel Schürmann
daschuer at mixxx.org
Wed Nov 5 11:26:45 CET 2025
On Wed, Nov 5, 2025 at 9:10 AM Arno Rehn <a.rehn at menlosystems.com> wrote:
> On 05.11.2025 08:22, Daniel Schürmann wrote:
> > However I am not confident that this bullet proved enough for being
> > integrated in the upstream library.
> > * It works by guessing the parent argument which can fail at runtime
> > without even a compiler message, in users code.
> > * It does not yet (<x++23) support constructors requiring a sub
> > class parent like QWidget or any other user defined sub class.
> > * We can make it more robust by constructing without parent and then
> > call setParent() causing some extra calls and bookkeeping. I
> > don't want that.
>
> Honestly I think you're over-engineering this somewhat. "parent comes
> last" is an established convention when dealing with QObject-derived
> classes. QWidgets are the same, see for example QPushButton:
>
> QPushButton(const QIcon &icon, const QString &text, QWidget *parent)
>
> Just forward the args and append "this" as the last parameter to pass
> the parent along.
>
> Re subclass parents: You don't actually need C++23 for that. We can
> (ab-)use a templated implicit conversion operator to auto-cast a type to
> the one required by the constructor:
>
> template<class Q>
> struct autocast
> {
> Q *v;
> template<class T>
> operator T*() const { return static_cast<T*>(v); }
> };
>
> template<class T, class... Args>
> QParentedPtr<T> createChild(Args&&... args) {
> return new T(std::forward<Args>(args)..., autocast<QObject>{this});
> }
>
> Full example on godbolt: https://godbolt.org/z/T8h6hWWzP
>
> Granted, this would allow someone to do
>
> QObject o;
> o.createChild<QWidget>();
>
> which would likely crash and burn at runtime, so there are tradeoffs..
>
> Cheers,
> Arno
>
> --
> Arno Rehn
> Principal Software Engineer
> Tel +49 89 189 166 0
> Fax +49 89 189 166 111
> a.rehn at menlosystems.com
> www.menlosystems.com
>
> Menlo Systems GmbH
> Bunsenstrasse 5, D-82152 Martinsried, Germany
> Amtsgericht München HRB 138145
> Geschäftsführung: Dr. Michael Mei, Dr. Ronald Holzwarth
> USt.-IdNr. DE217772017, St.-Nr. 14316170324
>
Hi Arno
"parent comes last" seems to be only a rule of thumb unfortunately. See
here:
https://github.com/search?q=repo%3Aqt%2Fqtbase+%22parent+%3D+nullptr%2C%22&type=code
Your autocast code is a nice Idea. It has hower no safety net for
incompatible casts:
See https://godbolt.org/z/f6fdrKddh
I have messed around with some static asserts, but I struggle with getting
the original type of "this"
qobject_cast() works at runtime.
Do you have an idea to do it at compile time?
Best regards,
Daniel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20251105/ca85c248/attachment-0001.htm>
More information about the Development
mailing list