C++核心准则C.83:对于值类类型,考虑提供一个不会抛出异常的交换...


C.83: For value-like types, consider providing a noexcept swap function
C.83:对于值类类型,考虑提供一个不会抛出异常的交换函数





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.
移动功能可以在实现很多常规操作时提供便利。从顺畅地移动对象到更容易地实现赋值,以至提供有保证的提交函数,这个函数可以为不会失败的调用代码提供强有力的支持。



class Foo {
public:
void swap(Foo& rhs) noexcept
{
m1.swap(rhs.m1);
std::swap(m2, rhs.m2);
}
private:
Bar m1;
int m2;
};
Providing a nonmember swap function in the same namespace as your type for callers' convenience.
为了调用者的方便,在和目标类型同一个命名空间中提供一个非成员的swap函数。
void swap(Foo& a, Foo& b)
{
a.swap(b);
}



(Simple) A class without virtual functions should have a swap member function declared.
(简单)不包含虚函数的类就应该定义一个swap函数。
(Simple) When a class has a swap member function, it should be declared noexcept.
(简单)如果一个类包含一个swap成员函数,这个函数应该被声明为noexcept。



https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c83-for-value-like-types-consider-providing-a-noexcept-swap-function
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!