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)
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;
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())
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.
source share