2 ms·
> Ooops... now I have a double-free! not in this case: when you call delete on field_ptr, it removes itself from the list of children of windows_ptr. The other
by jcelerier 9y ago
> Ooops... now I have a double-free!
not in this case: when you call delete on field_ptr, it removes itself from the list of children of windows_ptr. The other case would have crashed though.
But generally you don't even need to have new / delete / make_unique / whatever:
class MyWidget : public QWidget {
QFormLayout lay;
QPushButton button;
QLineEdit edit;
public:
MyWidget(QWidget* parent)
: QWidget{parent}
, lay{this}
{
button.setText("Hello world");
lay.addRow("Button", &button);
lay.addRow("Some text", &edit);
}
};
these cases will work just fine since everything will be deleted in the correct order.
Likewise, you can just store a std::vector<std::unique_ptr<QObject>> if it makes you sleep better at night, if the objects are child of the class in, which you're storing them.
> Even if they don't want to use `std::unique_ptr` or `std::shared_ptr`, they can create their own (hopefully easily compatible) `QInstance` and `QSharedInstance` or something similar.
There are already various smart pointer types in Qt. But would you really like them to add unique_ptr overloads everywhere ? I'd hate to have to do
auto my_widg_ptr = std::make_unique<MyWidget>();
auto my_widg = my_widg_ptr.get();
parent_layout->addWidget(std::move(my_widg_ptr));
connect(whatever, &foo::bar,
[=] { my_widg->do_stuff(); });
vs today's
auto my_widg = new MyWidget;
parent_layout->addWidget(my_widg);
connect(whatever, &foo::bar,
[=] { my_widg->do_stuff(); });
- inetknght 9y agoLearn something new every day. I like this. I think my point though is still valid: that it's implicit ownership rules which are not clear ownership rules.
- gmueckl 9y agoThe relationships are very clear in most code using Qt. When you create a QObject-derived object, one of the constructor parameters is always the parent. Little things like this goes a long way. I never felt the need to express ownership more explicitly with Qt. Whenever I felt the urge to do so, it turned out that I was trying to do something crazy that I probably shouldn't try in the first place...