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

 

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章