[Development] parented_ptr
Arno Rehn
a.rehn at menlosystems.com
Wed Nov 5 09:10:38 CET 2025
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
More information about the Development
mailing list