Convert (Qt) an object container to a const object container efficiently?

My particular problem is that I have a member of QMultiHash<Foo,Bar*> private , and I would like to provide access to the hash values, but for const versions of the elements, declaring:

 QList<const Bar*> getBars(Foo f) const; 

Is there a cleaner / more efficient way to โ€œstateโ€ elements inside a Qt container than the ugly / inefficient creation of a new container with const elements and copy pointers from the source ( QMultiHash<K,V>::values() in this case)?

I am afraid that the answer may be no, but I wanted to make sure that I did not miss any Qt / C ++ syntax magic (03) to do this.

+5
source share
2 answers

There are two ways. The obvious way you mentioned is to use C ++ 11 for and convert it directly to QList<const Bar*> .

 QList<const Bar*> getList() const { QList<const Bar*> list; for(Bar *b : m_List) //where m_List is your private memebr QList<Bar*> list << b; return list; } 

Another way is to convert QList itself to const QList<Bar*> , which can be done "magically" by returning a list from the const function, for example:

 const QList<Bar*> getList() const { return m_List; //where m_List is your private memebr QList<Bar*> } 

Which one to use depends on your needs. From what you described, you need to check the elements without changing them. It sounds like you donโ€™t need a mutable list at all. The first option sounds like a bust. You want const Bar* presumably because you do not want it to randomly change when you check an item. To view all the elements, for example, you could do (by adding const automatically for each element):

 for(const Bar *b : myObject->getList()) //do only const stuff with b 

If you donโ€™t have a really good reason to return QList<const Bar*> , for example, you need the list to be modifiable, it does not cost problems and performance. You can restrict Bar * to const when you access it yourself, using C ++ 11 for in the way I described, or using const iterators. From what I'm going to, I would recommend using this and not converting the (possibly huge) list to const.

And one last tip if your listings are really huge and you need every drop of performance:

 const QList<Bar*> &getList() const 

Implicit sharing of Qt does this in the previous code snippet, I believe, but it ensures that the list will never be copied or modified when it is checked.

0
source

There is no efficient way to โ€œcreateโ€ objects in an existing array. But if you really keep a list of pointers. Maybe quickly convert const const pointers to const pointers in a simple loop ?! (Ie make a new list) The second solution is to create const objects in the list initially when you populate this list. And the third way is to make your own class of children on your list, which can only return a "const" link or an iterator to the stored elements.

0
source

All Articles