56. Whenever it makes sense, provide a no-fail swap (and provide it correctly)

Summary

swap is both a lightweight and a workhorse: Consider providing a swap function to efficiently and infallibly swap the internals of this object with another’s. Such a function can be handy for implementing a number of idioms, from smoothly moving objects around to implementing assignment easily to providing a guaranteed commit function that enables strongly error-safe calling code. (See also Item 51.)

Discussion

A swap function typically looks like this, where U is some user-defined type:

image

For primitive types and for standard containers, std::swap will do. ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.