[Interest] qSwap or std::swap?

Thiago Macieira thiago.macieira at intel.com
Mon Oct 26 07:52:37 CET 2015


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




More information about the Interest mailing list