Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

C/C++

Object Swapping Part 1: Its Surprising Importance



Related Reading


More Insights




JonKalb

To emphasize the fundamental nature of swap(), I've coined to the term "swapparator" in my Exception-Safe Coding talk. There is a video of my talk here: http://exceptionsafecode.com

apais440

Hello,
Either I missed something or it is the well known copy&swap idiom (http://en.wikibooks.org/wik...

Zenju

This is old news, but nevertheless still doesn't get the attention it should in modern C++ design, so thanks for the refresher.

With C++11 there's a new reason to make "swap" a first-class citizen next to constructors, destructors and assignment operator: "Unifying assgiment"
http://en.wikibooks.org/wik...

For reference Herb Sutter on implementing assigment in terms of "swap" and it's benefit for exception safety:
http://www.gotw.ca/gotw/059...

chuan6

It's an interesting idea and a common approach to implement a new component by using existing components; but in this case, why not just treat copy, assignment, and swap as three basic object operations on their own?

JDINGLER750

This is good food for thought. You've made a good argument for exception handling.

I don't quite see this as a general purpose solution however.

I'll be interested to see how this could improve performance. I can imagine scenarios where this could temporarily improve performance, by deferring the destruction of child objects and the freeing of resources until after the meaty work is done.

For that you'd likely want most of your data laden members to be pointers, so that they can be swapped between objects with minimal overhead.

I'm drawing a blank on other scenarios that would benefit, as you seem to be increasing the amount of work done in an assignment, without eliminating any pre-existing steps. You've just changed the order.