快捷搜索:  汽车  科技

swap怎么不能用了(swap不应该失败)

swap怎么不能用了(swap不应该失败){void swap(My_vector& x My_vector& y)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(反面示例)

swap怎么不能用了(swap不应该失败)(1)

钒铅矿

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


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

更多精彩文章请关注微信公众号【面向对象思考】!

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

猜您喜欢: