C++核心準則C.84:swap函數(shù)不應該失敗

釩鉛礦
C.84: A swap function may not fail
C.84:swap函數(shù)不應該失敗



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函數(shù)被廣泛地使用的方式就是假設它永遠不會失敗,而且也很難寫出即使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的元素發(fā)生了內(nèi)存申請,如果使用它的話,這個swap可能拋出異常并令STL算法失敗。


Enforcement(實施建議)


(Simple) When a class has a swap member function, it should be declared noexcept.
(簡單)如果類包含swap成員函數(shù),它應該被聲明為noexcept。


原文鏈接


https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c84-a-swap-function-may-not-fail
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
