[Interest] qSwap or std::swap?

Philippe philwave at gmail.com
Mon Oct 26 08:22:56 CET 2015


You are right. I also just verified that:
qSwap(str1, str2)
and
swap(str1, str2)

produce both the same code.

while 
std::swap(str1, str2)
is different and produce far more assembly code.

As you say, this is a big gotcha, and using the qSwap is more obvious.
Therefore you should consider removing qSwap from the Qt official obsolete list...

Philippe

On Sun, 25 Oct 2015 23:52:37 -0700
Thiago Macieira <thiago.macieira at intel.com> wrote:

> On Monday 26 October 2015 07:44:55 Philippe wrote:
> > In the Qt doc, it is said that qSwap is obsolete and should never be used
> > in new code:
> > http://doc.qt.io/qt-5/qtalgorithms-obsolete.html
> > 
> > But in this recent video from the Qt World Summit 2015, Marc Mutz says the
> > exact opposite (around time 20:30)
> > https://www.youtube.com/watch?v=Y3YMA1Ip3ek
> > 
> > A quick test with Qt 5.5.1 on qSwap with QString tends to show Marc is
> > right (much less assembly code for this call).
> > 
> > So, is it a mistake from the Qt documentation or?...
> 
> Both are correct, since one is implemented in terms of the other. That means 
> they MUST expand to exactly the same assembly (and they do, I've just tested).
> 
> If you're seeing something different, the problem is probably your code. And 
> that's why Marc is recommending qSwap: because people don't know how to use 
> std::swap. There's a big gotcha: you MUST NOT write the "std::" part of 
> std::swap.
> 
> This is the correct way to swap two QStrings using std::swap:
> 
> 	swap(s1, s2);
> 
> Or, for a given type that you don't know about, you must write:
> 
> 	using namespace std;
> 	swap(t1, t2);
> 
> This is independent of your coding policies. You MUST use the namespace in 
> order to call std::swap. So if your coding policies is not to use it, then you 
> need to wrap it in { } to avoid the namespace usage leaking.
> 
> -- 
> Thiago Macieira - thiago.macieira (AT) intel.com
>   Software Architect - Intel Open Source Technology Center
> 
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> http://lists.qt-project.org/mailman/listinfo/interest





More information about the Interest mailing list