A QList<T *> can’t easily be const-correct. Consider the function
void f(QList<T *> list)
{
list[0]->constFunction();
}
I can change f to
void f(QList<const T *> list)
but then I can’t do
f(QList<T *>()); //Compile error
anymore, since the compiler can’t implicitely cast QList<T *> to QList<const T *>. However, I can explicitely reinterpret-cast the QList as follows:
template <typename T> inline QList<const T *> &constList(const QList<T *> &list)
{
return (QList<const T *> &)list;
}
This enables me to use the constList template function to cast any QList<T *> into a QList<const T *>, as in
f(constList(QList<T *>()));
and it seems to work fine, but is it actually safe to do this?
The casting function you’re considering, …
… may be practical (probably
QListdoes not change its object representation depending on theconst-ness of the element type), but it can breakconstcorrectness.First, because casting away the
const-ness of the list itself is notconstcorrect: it allows you to change an originallyconstlist.But even if that formal argument
constis removed, like …… there is still a
constcorrectness problem.The reason is that the list constitutes an additional level of indirection, and with your function is not itself
const. Thus, after using your function to get a reference to the list with alleged pointer-to-constelements, you can store in that list a pointer to something that is reallyconst. And then you can use the original list to modify that reallyconstitem, bang.It’s the same reason that there is no implicit conversion from
T**toT const**.What you can do without such problems is, with an already
constlist of pointers to objects, make those pointed to objectsconst:Formally there’s still the
reinterpret_castas a potential problem, but anyone specializating the representation ofQListon constness of elements would presumably deserve whatever they got. 🙂Cheers & hth.,