C++核心准则C.84:swap函数不应该失败

共 1059字,需浏览 3分钟

 ·

2020-01-20 23:24

daa308a5db176801e9badfdec57398f1.webp

钒铅矿


C.84: A swap function may not fail

C.84:swap函数不应该失败


d92962aaab42542349668ccd11792a40.webp5c48c265ff50e2e1077730cb006d2a25.webp
dc14be07096967365bb12e1cdf69a6ac.webp
Reason(原因)
dc14be07096967365bb12e1cdf69a6ac.webp
5c48c265ff50e2e1077730cb006d2a25.webp

swap is widely used in ways that are assumed never to fail and programs cannot easily be written to work correctly in the presence of a failing swap. The standard-library containers and algorithms will not work correctly if a swap of an element type fails.

swap函数被广泛地使用的方式就是假设它永远不会失败,而且也很难写出即使swap出错也能正常动作的程序。标准库容器和算法在元素交换失败时也无法正常工作。

5f2cbcef0743bcc9c3e0a8fc3aa1bdcb.webp
Example, bad(反面示例)
5f2cbcef0743bcc9c3e0a8fc3aa1bdcb.webp
void swap(My_vector& x, My_vector& y)
{
   auto tmp = x;   // copy elements
   x = y;
   y = tmp;
}

This is not just slow, but if a memory allocation occurs for the elements in tmp, this swap may throw and would make STL algorithms fail if used with them.

这段代码的问题不仅是慢,而且如果因为tmp的元素发生了内存申请,如果使用它的话,这个swap可能抛出异常并令STL算法失败。


5c48c265ff50e2e1077730cb006d2a25.webp
dc14be07096967365bb12e1cdf69a6ac.webp
Enforcement(实施建议)
dc14be07096967365bb12e1cdf69a6ac.webp
5c48c265ff50e2e1077730cb006d2a25.webp

(Simple) When a class has a swap member function, it should be declared noexcept.

(简单)如果类包含swap成员函数,它应该被声明为noexcept。


5c48c265ff50e2e1077730cb006d2a25.webp
dc14be07096967365bb12e1cdf69a6ac.webp
原文链接
dc14be07096967365bb12e1cdf69a6ac.webp
5c48c265ff50e2e1077730cb006d2a25.webp

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c84-a-swap-function-may-not-fail




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

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

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


浏览 9
点赞
评论
收藏
分享

手机扫一扫分享

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

手机扫一扫分享

分享
举报