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

共 1353字,需浏览 3分钟

 ·

2020-01-19 23:22

83cda04c50429b9b28dab969f3fc975e.webp

17837d93b3960a794bd61f6e121230be.webp
f96c6ff16c97849716454a8c123b0b37.webp

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

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


f96c6ff16c97849716454a8c123b0b37.webp
17837d93b3960a794bd61f6e121230be.webp


53583f5943f3991ddae6a06f78b193d0.webp47bfa6336ae1a5fddbe3ba3ac90a5c7d.webpReason(原因)47bfa6336ae1a5fddbe3ba3ac90a5c7d.webp

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.

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


53583f5943f3991ddae6a06f78b193d0.webp47bfa6336ae1a5fddbe3ba3ac90a5c7d.webpExample, good(示例)47bfa6336ae1a5fddbe3ba3ac90a5c7d.webp
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);
}
53583f5943f3991ddae6a06f78b193d0.webp47bfa6336ae1a5fddbe3ba3ac90a5c7d.webpEnforcement(实施建议)47bfa6336ae1a5fddbe3ba3ac90a5c7d.webp


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

53583f5943f3991ddae6a06f78b193d0.webp47bfa6336ae1a5fddbe3ba3ac90a5c7d.webp原文链接47bfa6336ae1a5fddbe3ba3ac90a5c7d.webp

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c83-for-value-like-types-consider-providing-a-noexcept-swap-function



觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

浏览 18
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报