Please nominate your Qt Champions for 2021!

Why foreach is not using const reference (it is making copies)?

  • Why QForeachContainer is using variable c defined as "const T c;" and not as "const T &c;"?
    I would expect that this means that during constructing of QForeachContainer in every foreach statement original container t of type T is copied from it (not const-referenced to it) with statement "c(t)" in the constructor of QForeachContainer.
    Why there is necessity in this overhead?

    Code from qglobal.h:

    template <typename T>
      class QForeachContainer {
        QForeachContainer &operator=(const QForeachContainer &) Q_DECL_EQ_DELETE;
        inline QForeachContainer(const T& t) : c(t), i(c.begin()), e(c.end()), control(1) { }
        const T c;
        typename T::const_iterator i, e;
        int control;

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    If you want to avoid the copy, you can use:

    foreach  (const QString &str, myStringList) {
        qDebug() << str;

  • @SGaist Mmm ... I was asking about copying of container object (which is myStringList in your example), not about its items. Did you get the question correctly?

  • Lifetime Qt Champion

    My bad, indeed, I misunderstood your question. The answer you are looking for is here in Qt's documentation

  • @SGaist Mmm ... documentation states that copying happens but I did not get Why this is done like that?
    I can not imagine good cases of using this container-copy feature of foreach ... to be able to modify container while looping through its hiddenly copied duplicate ... well ... this is something ... let's say special ;)

    May be such implementation of iterator-loop have the right to exist but in this case I would expect it to co-exist with another iterator-loop which works in more straightforward for developers way (with just const-ref to container).

  • Moreover Qt-containers tries to be stl-compatible and If Qt-developer is used to use foreach for Qt-containers it could be non-obvious for him/her that with stl-container the container data copying is happening every time foreach statement is used (as soon as stl-containers does not do implicit sharing)

    For me it is like very hidden trap.

  • Lifetime Qt Champion

    If you would like to discuss that issue further down, then I'd recommend asking it on the interest mailing list You'll find there Qt's developers/maintainers (this forum is mor e user oriented)

Log in to reply