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; public: 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; };
-
Hi and welcome to devnet,
If you want to avoid the copy, you can use:
foreach (const QString &str, myStringList) { qDebug() << str; }
-
@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.
-
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)