QMap<int, MyObject*> map;
// ^ ^
// | +-- T == "MyObject*"
// |
// +-- Key == "int"
QMap<int, MyObject*> map;
// ^ ^
// | +-- T == "MyObject*"
// |
// +-- Key == "int"
To copy to clipboard, switch view to plain text mode
The function QMap::value() returns a "const T", that is, "const MyObject*" (constant pointer-to-obj) not "MyObject const *" (pointer-to-const-obj) . In assigning that return value to a pointer variable you make a copy of it, which may or may not be const.
#include <QCoreApplication>
#include <QMap>
class MyObject {
public:
void constFunc() const { }
void nonConstFunct() { }
};
int main(int argc, char **argv) {
MyObject *a = new MyObject;
MyObject const *b = new MyObject;
QMap<int, MyObject *> map1;
map1.insert(0, a); // ok
// map1.insert(1, b); // error, cannot put pointer-to-const in map
MyObject *c = map1.value(0); // ok
MyObject const *d = map1.value(0); // ok
c->nonConstFunct(); // ok
// d->nonConstFunct(); // error, we promised d pointed to a const object
// You can have a map contain pointer-to-const-object
QMap<int, MyObject const *> map2;
map2.insert(0, a); // ok
map2.insert(1, b); // ok
// c = map2.value(0); // error, map cannot put "MyObject const *" into a non-const pointer var
d = map2.value(1); // ok
d->constFunc(); // ok, pointer-to-const and const function
// d->nonConstFunct(); // error, pointer-to-const and non-const function
delete a;
delete b;
return 0;
}
#include <QCoreApplication>
#include <QMap>
class MyObject {
public:
void constFunc() const { }
void nonConstFunct() { }
};
int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
MyObject *a = new MyObject;
MyObject const *b = new MyObject;
QMap<int, MyObject *> map1;
map1.insert(0, a); // ok
// map1.insert(1, b); // error, cannot put pointer-to-const in map
MyObject *c = map1.value(0); // ok
MyObject const *d = map1.value(0); // ok
c->nonConstFunct(); // ok
// d->nonConstFunct(); // error, we promised d pointed to a const object
// You can have a map contain pointer-to-const-object
QMap<int, MyObject const *> map2;
map2.insert(0, a); // ok
map2.insert(1, b); // ok
// c = map2.value(0); // error, map cannot put "MyObject const *" into a non-const pointer var
d = map2.value(1); // ok
d->constFunc(); // ok, pointer-to-const and const function
// d->nonConstFunct(); // error, pointer-to-const and non-const function
delete a;
delete b;
return 0;
}
To copy to clipboard, switch view to plain text mode
Bookmarks