[Development] unique_ptr and Qt

Daniel Teske qt at squorn.de
Sun Jun 17 21:16:05 CEST 2018


> Thanks for doing this.
>
> Here is what i suggest to make the change less intrusive:
> For the constructors themself in every classes.
>
>   // Removed the '=nullptr' default parent, and added QT_UNSAFE_API
>   QT_UNSAFE_API explicit QLineEdit(QWidget *parent);
>   QT_UNSAFE_API explicit QLineEdit(const QString &, QWidget *parent);
>   // Added new non-deprecated constructor not taking parent.
>   explicit QLineEdit(const QString & = {});
>
>
> //The QObject::makeChild method:
> template <class T, class... Args> T* QObject::makeChild(Args&&... args)
> {
>   auto n = new T(std::forward<Args>(args)...);
>   n->setParent(this);
>   return n;
> }
>
>
> That way, std::make_unique still work, and constructing objects on the 
> stack does not change.
>
> For the cases where the parent in the constructor has another meaning, 
> we would need another factory function (makeChild) in the relevant 
> class. Or interept the ParentChanged, or reimplement setParent in that 
> class.
>
> What do you think?
>
Consider this "old" code:

QWidget widget;
QVBoxLayout *topLayout = new QVBoxLayout(&widget);
QVBoxLayout *childLayout = new QVBoxLayout();
topLayout->addLayout(childLayout);

That would, if I understood you correctly, translate too:
QWidget widget;
QVboxLayout *topLayout = widget.makeChild<QVBoxLayout>();
auto childLayout = std::make_unique<QVBoxLayout>();
topLayout-addLayout(std::move(childLayout));

Both topLayout and childLayout do end up with the same parent. In the 
old code, the QLayout ctor which takes a parent widget, calls 
QWidget::setLayout.
Thus I think overriding setParent or interpreting ParentChanged would 
not work.

Though makeChild could work, that is we would need:

template <class T, class... Args> T* QWidget::makeChild(Args&&... args)
{
   auto n = new T(std::forward<Args>(args)...);
   n->setParent(this);

   if constexpr(std::is_base_of<QLayout, T>)
     setLayout(n);
   return n;
}

I guess whether that is feasible depends on many ctors assign additional 
semantics to the parent parameter.

daniel



More information about the Development mailing list