Problems with QList and const Class
-
Hello, I have a problem when using QList<MyCLass*>::contains() and QList<MyClass*>::indexOf() with const instances.
Here is my example code :
@#ifndef MAINWINDOW_HPP
#define MAINWINDOW_HPP#include <QList>
#include <QMainWindow>#define ERROR -9
class MyClass
{
private:
QString m_name;public: MyClass() : m_name("Default") {}
};
class MainWindow : public QMainWindow
{
Q_OBJECTQList<MyClass*> m_list; public: MainWindow() : QMainWindow(), m_list() {} int getIndexOf(const MyClass* myClass) const { if (m_list.contains(myClass)) { return m_list.indexOf(myClass); } else { return ERROR; } }
};
#endif // MAINWINDOW_HPP
@When compiling, I have those errors:
MainWindow.hpp:40: erreur : invalid conversion from 'const MyClass*' to 'MyClass*' [-fpermissive]
qlist.h:886: error: initializing argument 1 of 'bool QList<T>::contains(const T&) const [with T = MyClass*]' [-fpermissive]
MainWindow.hpp:42: erreur : invalid conversion from 'const MyClass*' to 'MyClass*' [-fpermissive]
qlist.h:853: error: initializing argument 1 of 'int QList<T>::indexOf(const T&, int) const [with T = MyClass*]' [-fpermissive]I do not realy understand why because those methodes are expected constant template :
QList::contains(const T&)
and here, T = MyClass* and I send a const MyClass* in parameter. -
There's a difference between a constant pointer to MyClass and a pointer to a constant MyClass. The getIndexOf Method has the latter kind as parameter, the QList methods expect the first kind.
Look:
int a;
someList.contains(a);
the "const T&" of QList::contains guarantees, that a won't be changed.Similarly:
MyClass *a;
someList.contains(a);
guarantees, that a won't be changed. a, the pointer value (32/64-bit number). It's very different from const MyClass *a, which guarantees that *a, the object the 32/64-bit number points to, won't be changed.Solution: try const_cast, or change the list type to const MyClass*
//EDIT: Something to think about along those lines:
@int i;
QList<const int> a;
QList<const int*> b;
a << i;
b << &i;
@
What will work, what will fail? Which list can/can't do what? -
Ok,
I understand the problem. Thanks for your help.