Qt is equivalent to boost :: ptr_vector?

I need a pointer container that takes control of the pointers - i.e. when an element is deleted or the container goes out of scope, it frees all its pointers, for example, in boost::ptr_vector .

QList<QScopedPointer<AbstractClass> > does not work (compile errors, no copy constructor?).

I am currently using QList<QSharedPointer<AbstractClass> > , but it feels redundant with reference counting and an expensive mutex for multithreading.

Edit: I just found out about QPtrList (thanks @ForEveR), which was very similar to Qt3, but was removed from later versions. I just don’t understand why they would delete it.

+6
source share
2 answers

You are right that QSharedPointer is a little overhead for the reasons indicated.

Unfortunately, Qt does not have such a pointer vector, and it is also a little doubtful whether to add it when the language develops, and we have good primitives for doing such tasks.

I just had a quick discussion with one of the Qt core developers, and it seems like the recommended solution for today is QSharedPointer or this is from C ++ 11:

 std::vector<std::unique_ptr<AbstractClass>> 

Do not try to use QVector instead of std :: vector, as QVector may want to make copies.

Do not try to use this solution even in C ++ 11:

 QList<QScopedPointer<AbstractClass>> 

The problem is that QList wants to make copies. When using any non-constant method, detach is called, which makes copies, and this will not be a compiler.

In addition, QScopedPointer does not have constructors or movement operators, and which are by design .

+4
source

Another idea based on Qt concepts:

You can get the objects that the pointer in the list shows from a QObject, and add a small QObect-based class that contains the ownership of the list. Each pointer that will be added to this new QObject-based list must set its own list class as its parent. Now the QObject-based container list will take care of clearing with the Qt mechanism when it is freed.

 class Ptr : public QObject { }; class MyList : public QObject { QList<Ptr> m_myList; public: void add( Ptr *item ) { m_mylist.push_back( item ); item->setParent( this ); } }; 

Here you can find more information about the owner of the Qt object tree: http://qt-project.org/doc/qt-4.8/objecttrees.html .

Of course, this is a lot more overhead than using the small type C ++ - 11 type std :: unique_ptr.

0
source

Source: https://habr.com/ru/post/979771/


All Articles