swap

closed account (jGAShbRD)
do u know whats the difference between storage.swap(new_storage) and std::swap(storage,new_storage), also does it have to be std::storage.swap(new_storage) if i didnt include namespace std or is just storage.swap() fine?
Typically, prefer the specialized a.swap(b) over the more generic std::swap(a, b) when the former exists.

This is good enough advice for most cases, but there's more to the story.

Typically, when the former exists, there is also a namespace-scope overload of swap visible via argument-dependent lookup. For ADL to occur, the function name must be an unqualified-id, i.e., std:: must not appear on the left, as in
/*std::*/swap(a, b)
And this will typically do the right thing.

In generic code, the invocation
1
2
using std::swap;
swap(a, b);

Is sometimes used so that ADL has an opportunity to find custom swap overloads, and if that fails, generic std::swap is available as a fall-back.

ADL can cause very surprising behavior, even for experts. It is a secondary reason I suggest that students avoid using namespace.
Last edited on
Topic archived. No new replies allowed.