[Development] How qAsConst and qExchange lead to qNN

Thiago Macieira thiago.macieira at intel.com
Wed Nov 16 18:50:35 CET 2022

On Tuesday, 15 November 2022 23:50:38 PST Marc Mutz via Development wrote:
> > in a thread-safe manner (such that if something in
> > the same thread or another thread-safely modifies that map, the original
> > user isn't affected).
> The above isn't thread-safe, it isn't even re-entrant, in the same way
> that iteration using iterators isn't. This is a known issue whenever you
> hand out references, and it's nothing that violates our
> const-is-thread-safe promise, 

No, but it moves the responsibility for avoiding this problem to the user.

Right now, you can do:
  for (auto elem : object.keyList()) {
      operate(); // may recurse back into object and modify it

If you use a generator paradigm to return this key list, then the *user* must 
know that they must create a local container with the items to be generated 
and iterate over that. Performance-wise, this no different than if the Qt code 
created the container and returned it, but it has two drawbacks:

1) the responsibility for knowing this

2) if the Qt object already has a QList with this, then using a generator 
paradigm enforces the need of a deep copy, when implicit would have been 

> > Because you pointed to QStringTokenizer and that implicitly-
> > copies a QString.
> That's imprecise. QStringTokenizer extends rvalue lifetimes ("rvalue
> pinning") so's to make this safe:
>     for (auto part : qTokenize(label->text(), u';'))

BTW, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2012r2.pdf is 
accepted for C++23 and moves the end of the temporaries' lifetimes to the end 
of the full for statement.

Though we still need to work with C++17 and 20 for a while.

Also, sometimes I wonder if all the work you and I do to optimise these things 
matter, in the end. We may save 0.5% of the CPU time, only for that to be 
dwarfed by whatever QtGui, QtQml are doing.

Thiago Macieira - thiago.macieira (AT) intel.com
  Cloud Software Architect - Intel DCAI Cloud Engineering

More information about the Development mailing list