There are two ways. The obvious way you mention is to use C++11 for and convert it yourself 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;
}
The other way is to convert the QList
itself to const QList<Bar*>
which can be done "magically" by returning the list from a const function for instance:
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 describe you need to inspect the elements without changing them. That sounds like that you do not actually need the modifiable list at all. The first variant sound like an overkill already. You want const Bar*
presumably because you do not want it to change by accident when you inspect the item. To examine all elements for example you could do (adding const automatically for each element):
for(const Bar *b : myObject->getList())
//do only const stuff with b
Unless you have a really good reason for returning QList<const Bar*>
such as that you need the list to be modifiable it is not worth the trouble and performance hit. You can restrict Bar *
with const when you access it yourself by using the C++11 for
in a way I described or by using const iterators. From what I gather I would recommend using that rather than converting (possibly huge) list(s)' values to const.
And one last tip, if your lists are really huge and you need every drop of performance consider:
const QList<Bar*> &getList() const
The implicit sharing of Qt does this in the previous code snippet on its own I believe but this ensures the list will never be copied or modified when you inspect it.