0
点赞
收藏
分享

微信扫一扫

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


C.83: For value-like types, consider providing a noexcept swap function

C.83:对于值类类型,考虑提供一个不会抛出异常的交换函数

 

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 nonmember swap function in the same namespace as your type for callers' convenience.

为了调用者的方便,在和目标类型同一个命名空间中提供一个非成员的swap函数。

void swap(Foo& a, Foo& b)
{
a.swap(b);
}


Enforcement(实施建议)

  • (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​​

 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

举报

相关推荐

c++实现一个日期类

一个简单的c++函数调用

0 条评论