QList of QScopedPointers

我的未来我决定 提交于 2019-12-01 22:44:27

Values stored in Qt containers should be of assignable data types. That means they should have a default constructor, a copy constructor, and an assignment operator.

QScopedPointer has its copy constructor and assignment operator disabled. You can't assign two pointers to each other, but you can explicitly transfer the ownership of the underlying raw pointer using QScopedPointer::reset, QScopedPointer::swap or QScopedPointer::take.

At some point a move constructor and a move assignment operator were added to QScopedPointer. New move semantics made this possible:

QList<QScopedPointer<Label>> mLabels;
mLabels.append(QScopedPointer<Label>(new Label));

Here a temporary value is added to a list and the new list item is created using the move constructor.

Later they reverted that change:

Adding a move contructor to QScopedPointer makes no sense, because moving means 'escaping the scope', which breaks the fundamental point of QScopedPointer.

If you really want to have a list of smart pointers, you can use QSharedPointer which is assignable or std::unique_ptr which supports move semantics.

And if you talk about tracking lifetime of QObjects subclasses and especially widgets, I would suggest to use Qt child-parent mechanism rather than smart pointers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!