std::swap()

Hello,

I've read that the std::swap() function is valid for any data type, as long as they can be copied. Does this also hold for user-defined types?
The short answer is yes.

The longer answer is that there are more technical terms describing the constraints on types you want to use it with, but so long as you're not doing anything exotic with your copy or moves, should be fine.

To swap user-defined types, use unqualified swap:

1
2
3
// std::swap(a,b) ; // *** no
using std::swap ;
swap( a, b ) ; // yes 


To make a user defined type swappable,
Typical implementations either

1) Define a non-member swap in the enclosing namespace, which may forward to a member swap if access to non-public data members is required
2) Define a friend function in-class (this approach hides the class-specific swap from name lookup other than ADL)
https://en.cppreference.com/w/cpp/named_req/Swappable
@JLBorges, your link was interesting reading. Something at the link was even more interesting. std::iter_swap() and the is_swappable() family of template functions.

https://en.cppreference.com/w/cpp/algorithm/iter_swap

https://en.cppreference.com/w/cpp/types/is_swappable (C++17)
@JLBorges

what's the difference between the two versions you wrote?
@kyrresc:
Read about name lookup:
https://en.cppreference.com/w/cpp/language/lookup
https://en.cppreference.com/w/cpp/language/adl

std::swap( a, b ); looks "swap" from qualified scope "std": https://en.cppreference.com/w/cpp/language/qualified_lookup

swap( a, b ); looks for unqualified "swap": https://en.cppreference.com/w/cpp/language/unqualified_lookup and ADL

If you do supply a function "swap" for the type of a and b, then it will not be in the namespace "std" and cannot be found by the qualified lookup.
If you do supply a function "swap" for the type of a and b, then it surely is more proper for that type than the template of swap in the namespace std.

The unqualified lookup can find the "swap" from namespace std only if type of a or b is in namespace std (the ADL), or if identifiers from namespace std have been brought to current scope (by using).
Topic archived. No new replies allowed.