Should I use Qt containers or the std ones?

If you come from plain vanilla C++, you only know the C++ Standard Library with its containers like std::vector. If you know how to use them, you can accomplish your tasks pretty fast. But if you’re coming from an other language, the naming might be a bit odd. The Qt containers offer both, C++ style and Java style naming of methods. So coming from an other language the Qt ones might be easier to use.
The Qt containers use the COW (Copy on Write) technique to be able to create cheap copies of them. This technique uses an internal container to store all the data. This container is accessed by a pointer. If you copy the instance of e.g. the QList you get a new QList instance with a pointer to the exact same internal container. You can use the new list exactly like the old one. The internal container stays shared while the list is not modified. But any operation that modifies one of the lists, e.g. adding or removing of elements, will result in a detach before the modifying operation is performed. Detach means here, that the whole internal container is copied. After the detach you have two completely independent lists with two independent internal containers.

So if you pass a QList to a function or method (by value), the act of copying will be very cheap. As long as you don’t modify the list inside the function or method, you have saved yourself some RAM.

The std containers doesn’t use this technique to be fast and to know exactly how long each operation will take. If you pass a std::vector to a function or method (by value) the whole vector will be copied.

But be careful, Qt containers can have some strange behavior if you use them with C++14. If you use the new for(Element e: list) syntax, on a QList (that has been copied) you cannot be sure if it copies the internal container, because using the new syntax could modify it.

Right now I didn’t answer the question, which containers are the best ones to use. And in fact there is no golden answer to this question; there maybe never will. So the answer I can give you to this question today, is the same you maybe heard many times before at other topics: It depends. Obviously it’s overkill to use the Qt framework just because of its containers.

Maybe it’s better to use std, in fact many of the Qt containers use the std containers under the hood. But if you interact with the Qt library you will see, that you will tend to use the Qt containers. Just because it’s easier to use them, as to convert back and forth. And yes I know, some people recommend to use std instead of Qt as much as possible. Personally I use both, Qt for convenience and std if speed is an issue. The one thing I’m pretty sure about, is that there is no ultimate answer to this question.

Niclas Roßberger

Niclas Roßberger

Hi, I'm Niclas.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.