您的位置 首页 > 腾讯云社区

C++核心准则C.84:swap函数不应该失败---面向对象思考

钒铅矿

C.84: A swap function may not fail

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

Reason(原因)

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出错也能正常动作的程序。标准库容器和算法在元素交换失败时也无法正常工作。

Example, bad(反面示例)

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算法失败。

Enforcement(实施建议)

(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#c84-a-swap-function-may-not-fail

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

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

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

---来自腾讯云社区的---面向对象思考

关于作者: 瞎采新闻

这里可以显示个人介绍!这里可以显示个人介绍!

热门文章

留言与评论(共有 0 条评论)
   
验证码: