C ++ core principles C.84: swap functions should not fail

C.84: A swap function may not fail

C.84: swap function should not fail

 

 

Reason (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.

 

 

Way swap function is widely used is the assumption that it will never fail, but also difficult to write error can even swap the normal operation of the program. Standard Library containers and algorithms can not work properly when switching element failure.

 

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.

The problem with this code is not only slow, but if memory applications because the elements tmp occurs, if you use it, then this swap may throw an exception and let STL algorithm fails.

 

 

  Enforcement (Suggestions)

 

 

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

 

(Simple) if the class contains swap member function, it should be declared as noexcept.

 

 

Description link

 

 

 

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

 

 


 

I think this article helpful? Welcome thumbs up and share it with more people.

Read more updated articles, please pay attention to micro-channel public number of object-oriented thinking []

Published 408 original articles · won praise 653 · views 290 000 +

Guess you like

Origin blog.csdn.net/craftsman1970/article/details/104882804