{"id":6494,"date":"2022-12-18T10:11:19","date_gmt":"2022-12-18T10:11:19","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/the-copy-and-swap-idiom\/"},"modified":"2022-12-18T10:11:19","modified_gmt":"2022-12-18T10:11:19","slug":"the-copy-and-swap-idiom","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/the-copy-and-swap-idiom\/","title":{"rendered":"The Copy-and-Swap Idiom"},"content":{"rendered":"<p>An idiom is an architectural or design pattern implementation in a concrete programming language. Applying them is idiomatic for a programming language. Today. I write about the Copy-and-Swap Idiom in C++. This idiom gives you the strong exception safety guarantee.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6493\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/12\/GeneralIdioms.png\" alt=\"GeneralIdioms\" width=\"650\" height=\"331\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/12\/GeneralIdioms.png 1233w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/12\/GeneralIdioms-300x153.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/12\/GeneralIdioms-1024x521.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/12\/GeneralIdioms-768x391.png 768w\" sizes=\"auto, (max-width: 650px) 100vw, 650px\" \/><\/p>\n<p>Before I write about the Copy-and-Swap Idiom, I should first clarify the strong exception safety guarantee. Here are a few general thoughts about error handling:<\/p>\n<h2>Error Handling<\/h2>\n<p>When you handle an error, the following aspects should be considered:<\/p>\n<ul>\n<li>Detect an error<\/li>\n<li>Transmit information about an error to some handler code<\/li>\n<li>Preserve the valid state of a program<\/li>\n<li>Avoid resource leaks<\/li>\n<\/ul>\n<p>You should use exceptions for error handling. In the document &#8220;<a href=\"https:\/\/www.boost.org\/community\/exception_safety.html\">Exception-Safety in Generic Components<\/a>&#8221; <a href=\"https:\/\/en.wikipedia.org\/wiki\/David_Abrahams_(computer_programmer)\">David Abrahams<\/a> formalized what exception-safety means.<\/p>\n<h3>Abrahams Guarantees<\/h3>\n<p>Abrahams Guarantees describe a contract that is fundamental if you think about exception safety. Here are the four levels of the contract:<\/p>\n<ol>\n<li><strong>No-throw guarantee<\/strong>, also known as<strong> failure transparency<\/strong>: Operations are guaranteed to succeed and satisfy all requirements, even in exceptional situations. If an exception occurs, it is handled internally and cannot be observed by clients.<\/li>\n<li><strong>Strong exception safety<\/strong>, also known as <strong>commit<\/strong> or <strong>rollback semantics<\/strong>: Operations can fail, but failed operations are guaranteed to have no side effects, so all data retain their original values.<\/li>\n<li><strong>Basic exception safety<\/strong>, also known as a <strong>no-leak guarantee:<\/strong> Partial execution of failed operations can cause side effects, but all invariants are preserved, and there are no resource leaks (including memory leaks). Any stored data contains valid values, even if they differ from what they were before the exception.<\/li>\n<li><strong>No exception safety<\/strong>: No guarantees are made.<\/li>\n<\/ol>\n<p>In general, you should at least aim for the basic exception safety guarantee. This means that you don&#8217;t have resource leaks in case of an error, and your program is always in a well-defined state. If your program is not in a well-defined state after an error, there is only one option left: shut down your program.<\/p>\n<p>I stated that the Copy-and-Swap Idiom provides a strong exception safety guarantee. This is a stronger guarantee such as the basic exception safety guarantee.<\/p>\n<\/p>\n<h2>The Copy-and-Swap Idiom<\/h2>\n<p>Okay, I know what copy means. Therefore, let me write about swap:<\/p>\n<h3>The <code>swap<\/code> function<\/h3>\n<p>For a type to be a regular type, it has to support a <code>swap<\/code> function. A more informal definition of regular type is a value-like type that behaves like an <code>int<\/code>. I will write about regular types in an upcoming post. According to the rules &#8220;<a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-swap\">C.83: For value-like types, consider providing a noexcept swap function<\/a>&#8221; and &#8220;<a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-swap-noexcept\">C.85: Make swap noexcept<\/a>&#8221; of the C++ Core Guidelines, a <code>swap<\/code> function should not fail and be <code>noexcept<\/code>.<\/p>\n<p>The following data type Foo has a <code>swap<\/code> function.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Foo<\/span> {\r\n <span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> swap(Foo<span style=\"color: #555555;\">&amp;<\/span> rhs) noexcept {\r\n        m1.swap(rhs.m1);\r\n        std<span style=\"color: #555555;\">::<\/span>swap(m2, rhs.m2);\r\n    }\r\n <span style=\"color: #9999ff;\">private:<\/span>\r\n    Bar m1;\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> m2;\r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>For convenience reasons, you should consider supporting a non-member swap function based on the already implemented swap member function.<br \/> <!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">swap<\/span>(Foo<span style=\"color: #555555;\">&amp;<\/span> a, Foo<span style=\"color: #555555;\">&amp;<\/span> b) noexcept {\r\n    a.swap(b);\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>If you do not provide a non-member <code>swap<\/code> function, then the standard library algorithms that require swapping (such as<code> std::sort<\/code> and <code>std::rotate<\/code>) will fall back to the<code> std::swap<\/code> template, which is defined in terms of move construction and move assignment.<br \/><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">template<\/span><span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">typename<\/span> T<span style=\"color: #555555;\">&gt;<\/span>\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> std<span style=\"color: #555555;\">::<\/span>swap(T<span style=\"color: #555555;\">&amp;<\/span> a, T<span style=\"color: #555555;\">&amp;<\/span> b) noexcept {\r\n    T tmp(std<span style=\"color: #555555;\">::<\/span>move(a));\r\n    a <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>move(b);\r\n    b <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>move(tmp);\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The C++ standard offers more than 40 overloads of <a href=\"https:\/\/en.cppreference.com\/w\/cpp\/algorithm\/swap\"><code>std::swap<\/code><\/a>. You can use the <code>swap<\/code> function as a building block for many idioms, such as copy construction or move assignment.<\/p>\n<p>This brings me to the Copy-and-Swap Idiom.<\/p>\n<h3>Copy-And-Swap<\/h3>\n<p>If you use the Copy-and-Swap Idiom to implement the copy assignment and the move assignment operator, you must define your own swap \u2014 either as a member function or as a friend. I added a <code>swap<\/code> function to the class <code>Cont<\/code> and used it in the copy assignment and move assignment operator.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Cont<\/span> {\r\n <span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n    Cont<span style=\"color: #555555;\">&amp;<\/span> <span style=\"color: #006699; font-weight: bold;\">operator<\/span> <span style=\"color: #555555;\">=<\/span> (<span style=\"color: #006699; font-weight: bold;\">const<\/span> Cont<span style=\"color: #555555;\">&amp;<\/span> rhs);\r\n    Cont<span style=\"color: #555555;\">&amp;<\/span> <span style=\"color: #006699; font-weight: bold;\">operator<\/span> <span style=\"color: #555555;\">=<\/span> (Cont<span style=\"color: #555555;\">&amp;&amp;<\/span> rhs) noexcept;\r\n    <span style=\"color: #006699; font-weight: bold;\">friend<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">swap<\/span>(Cont<span style=\"color: #555555;\">&amp;<\/span> lhs, Cont<span style=\"color: #555555;\">&amp;<\/span> rhs) noexcept {\r\n        swap(lhs.size, rhs.size);\r\n        swap(lhs.pdata, rhs.pdata);\r\n}\r\n <span style=\"color: #9999ff;\">private:<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">*<\/span> pData;\r\n    std<span style=\"color: #555555;\">::<\/span><span style=\"color: #007788; font-weight: bold;\">size_t<\/span> size;\r\n};\r\n\r\nCont<span style=\"color: #555555;\">&amp;<\/span> Cont<span style=\"color: #555555;\">::<\/span><span style=\"color: #006699; font-weight: bold;\">operator<\/span> <span style=\"color: #555555;\">=<\/span> (<span style=\"color: #006699; font-weight: bold;\">const<\/span> Cont<span style=\"color: #555555;\">&amp;<\/span> rhs) {\r\n    Cont tmp(rhs);              <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n    swap(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>, tmp);          <em><span style=\"color: #0099ff;\"> \/\/ (3)<\/span><\/em>\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>;\r\n}\r\n\r\nCont<span style=\"color: #555555;\">&amp;<\/span> Cont<span style=\"color: #555555;\">::<\/span><span style=\"color: #006699; font-weight: bold;\">operator<\/span> <span style=\"color: #555555;\">=<\/span> (Cont<span style=\"color: #555555;\">&amp;&amp;<\/span> rhs) {\r\n    Cont tmp(std<span style=\"color: #555555;\">::<\/span>move(rhs));  <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n    swap(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>, tmp);          <em><span style=\"color: #0099ff;\">\/\/ (3)<\/span><\/em>\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>;\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Both assignment operators make a temporary copy<code> tmp<\/code> of the source object (lines 1 and ) and then apply the <code>swap<\/code> function to it (lines 3 and 4). When the used <code>swap<\/code> functions are <code>noexcept<\/code>, the copy assignment operator and the move assignment operator support the strong exception safety guarantee. This means that both assignment operators guarantee that the operations call will be fully rolled back in case of an error such as the error never happened.<\/p>\n<p>Operations supporting the Copy-and-Swap Idiom allow you to program in a transaction-based style. You prepare an operation (working on the copy) and publish the operation (swap the result) when it is fine. The Copy-and-Swap Idiom is a very powerful idiom that is applied pretty often.<\/p>\n<ul>\n<li><strong>Concurrent programming<\/strong>: You make your modification on a local object. This is, by definition, thread-safe because the data is not shared. When you are done with your change, you overwrite the shared data with your local data in a protected way.<\/li>\n<li><strong>Version control system<\/strong>: First, you check out the data and get a local copy. When you are done with your change, you commit your change and have to handle merge conflicts eventually. In case you cannot solve the merge conflict, you throw away your local change and check out once more.<\/li>\n<\/ul>\n<p>When a <code>swap<\/code> function is based on copy semantics instead of move semantics, a <code>swap<\/code> function may fail because of memory exhaustion. The following implementation contradicts the C++ Core Guidelines rule &#8220;<a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-swap-fail\">C++94: A <code>swap<\/code> function must not fail<\/a>&#8220;.This is the C++98 implementation of<code> std::swap<\/code>.<\/p>\n<p>&nbsp;<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">template<\/span><span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">typename<\/span> T<span style=\"color: #555555;\">&gt;<\/span>\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> std<span style=\"color: #555555;\">::<\/span>swap(T<span style=\"color: #555555;\">&amp;<\/span> a, T<span style=\"color: #555555;\">&amp;<\/span> b) {\r\n    T tmp <span style=\"color: #555555;\">=<\/span> a;\r\n    a <span style=\"color: #555555;\">=<\/span> b;\r\n    b <span style=\"color: #555555;\">=<\/span> tmp;\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>&nbsp;In this case, memory exhaustion may cause a <code>std::bad_alloc<\/code> exception.<\/p>\n<h2>What&#8217;s Next?<\/h2>\n<p>Partial Function Application is a technique in which a function binds a few of its arguments and returns a function taking fewer arguments. This technique is related to a technique used in functional languages called currying.<\/p>\n<h2>A Short Break<\/h2>\n<p>I will make a short two weeks Christmas Break. My next post will be published on Monday, the 9th of January. Have a good time,<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" alignleft size-full wp-image-6403\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/07\/RainerGrimmDunkelBlauSmall.jpg\" alt=\"RainerGrimmDunkelBlauSmall\" width=\"222\" height=\"67\" style=\"float: left;\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>An idiom is an architectural or design pattern implementation in a concrete programming language. Applying them is idiomatic for a programming language. Today. I write about the Copy-and-Swap Idiom in C++. This idiom gives you the strong exception safety guarantee.<\/p>\n","protected":false},"author":21,"featured_media":6493,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[379],"tags":[],"class_list":["post-6494","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-patterns"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6494","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=6494"}],"version-history":[{"count":0,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6494\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/6493"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=6494"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=6494"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=6494"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}