Effective Qt: Understand the Qt Containers
2011-08-15 3 Comments
If you know me, you will know what awaits you there I hope I have not disappointed you. That said, this is just a first part. I plan to eventually extend it to cover more containers (currently, just
QList), and give more data and assembler code for the containers I’ve already described.
These are the guidelines this item covers:
- Remember that QList has nothing to do with std::list, and QSet has nothing to do with std::set.
- Be aware of the two Qt container APIs, Qt-ish and STL-compatible, and avoid mixing their use in the same project.
- Familiarise yourself with the STL containers and the additional features they offer.
- Prefer member-swap over assignment wherever possible to express move semantics. Use C++11 rvalue move semantics if the class and the compiler support them.
- [[EDIT 2011-08-25: new]] Always use
cend()) when assigning the result to a
- Avoid modifying a container (remove/insert elements) while iterating. If you have to, use an STL algorithm, such as one of the
- Prefer the STL-compatible iterators over the Java-style ones.
- If you do use the Java-style iterators, avoid using the mutating ones.
- Prefer to use const references as the first argument of
Q_FOREACH, unless the element type is customarily passed by value.
- Familiarise yourself with
BOOST_FOREACH, and the additional features it offers.
- Declare your enums and
Q_PRIMITIVE_TYPEif there’s a chance they will be held in Qt containers.
- Declare your value-types
Q_MOVABLE_TYPEif there’s a chance they will be held in Qt containers.
- Don’t change the classification of a type if you need to maintain binary compatibility.
Tis not declared as either
sizeof(T) != sizeof(void*)(remember to check both 32 and 64-bit platforms).
- [[EDIT 2011-08-16: new]] Avoid using vectors of types for which Qt APIs customarily use
QList, and for which
QListis not inefficient.
Hope you enjoy!