Classes and class hierarchies
C.83
For value-like types, consider providing a `noexcept` swap function
Reason
A swap can be handy for implementing a number of idioms, from smoothly moving objects around to implementing assignment easily to providing a guaranteed commit function that enables strongly error-safe calling code. Consider using swap to implement copy assignment in terms of copy construction. See also destructors, deallocation, and swap must never fail.
Example, good
class Foo {
public:
void swap(Foo& rhs) noexcept
{
m1.swap(rhs.m1);
std::swap(m2, rhs.m2);
}
private:
Bar m1;
int m2;
};
Providing a non-member swap function in the same namespace as your type for callers' convenience.
void swap(Foo& a, Foo& b)
{
a.swap(b);
}
Enforcement
- Non-trivially copyable types should provide a member swap or a free swap overload.
- (Simple) When a class has a
swapmember function, it should be declarednoexcept.