[Interest] qSwap or std::swap?

Thiago Macieira thiago.macieira at intel.com
Mon Oct 26 18:11:55 CET 2015


On Monday 26 October 2015 08:48:55 John Weeks wrote:
> > 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.
> 
> At the risk of making a fool of myself, what is the difference? I thought I
> had learned that namespaces were just a scoping mechanism for names to
> avoid name collisions. Why does this make such a difference in the
> generated code?

Like Konstantin answered, this is due to Argument Dependent Lookup. You may 
not have known it happens with non-templates, but it does.

A call f(x) where x is of type N::X will first search for N::f(N::X), then 
walk through a very complex list of associated namespaces.

> I'm old enough now that the risk of making a fool of myself is a small price
> to pay in order to learn something.

Don't worry. ADL is one of the most complex and obscure corners of C++. It's 
several pages long in the standard, all started from an innocent-looking idea, 
"wouldn't it be nice if f(x) called N::f(N::X)?".

I think it's only less complex than overload resolution, but overloads are 
better understood (you can't live without them). I mean, overloads without 
templates... that gets complex again.

-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel Open Source Technology Center




More information about the Interest mailing list