{"id":5317,"date":"2017-09-15T19:13:55","date_gmt":"2017-09-15T19:13:55","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-copy-and-move-rules\/"},"modified":"2023-06-26T12:06:31","modified_gmt":"2023-06-26T12:06:31","slug":"c-core-guidelines-copy-and-move-rules","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-copy-and-move-rules\/","title":{"rendered":"C++ Core Guidelines: Rules for Copy and Move"},"content":{"rendered":"<p>The rules for copy and move are pretty obvious. But before I describe them I have to write about the two remaining rules for constructors. They are about delegating and inheriting constructors.<\/p>\n<p><!--more--><\/p>\n<p>Here are the two remaining rules:<\/p>\n<h2>Constructor Rules<\/h2>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" alignright size-full wp-image-5311\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/stork-1324371_1280.png\" alt=\"stork 1324371 1280\" width=\"400\" height=\"323\" style=\"float: right;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/stork-1324371_1280.png 1280w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/stork-1324371_1280-300x243.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/stork-1324371_1280-1024x828.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/stork-1324371_1280-768x621.png 768w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-delegating\">C.51: Use delegating constructors to represent common actions for all constructors of a class<\/a><\/h3>\n<p>Since C++11, a constructor can delegate its work to another constructor of the same class. This is the modern way in C++ to put common actions for all constructors in one constructor. In C++ code before C++11, you often used for such a job an <span style=\"font-family: courier new,courier;\">init<\/span> function.<\/p>\n<div style=\"background: #f0f3f3 none repeat scroll 0% 0%; overflow: auto; width: auto; border-width: 0.1em 0.1em 0.1em 0.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;\">Degree<\/span>{\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n  Degree(<span style=\"color: #007788; font-weight: bold;\">int<\/span> deg){                                           <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n    degree<span style=\"color: #555555;\">=<\/span> deg <span style=\"color: #555555;\">%<\/span> <span style=\"color: #ff6600;\">360<\/span>;\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (degree <span style=\"color: #555555;\">&lt;<\/span> <span style=\"color: #ff6600;\">0<\/span>) degree <span style=\"color: #555555;\">+=<\/span> <span style=\"color: #ff6600;\">360<\/span>;\r\n  }\r\n\r\n  Degree()<span style=\"color: #555555;\">:<\/span> Degree(<span style=\"color: #ff6600;\">0<\/span>){}                                      <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n\r\n  Degree(<span style=\"color: #007788; font-weight: bold;\">double<\/span> deg)<span style=\"color: #555555;\">:<\/span> Degree(<span style=\"color: #006699; font-weight: bold;\">static_cast<\/span><span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">&gt;<\/span>(ceil(deg))){}  <span style=\"color: #0099ff; font-style: italic;\">\/\/ (3)<\/span>\r\n\r\n<span style=\"color: #9999ff;\">private:<\/span>\r\n  <span style=\"color: #007788; font-weight: bold;\">int<\/span> degree;\r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The constructors (2) and (3) of the class <span style=\"font-family: courier new,courier;\">Degree<\/span> delegate all its initialization work to the constructor (1), which verifies its arguments. Invoking constructors recursively is undefined behavior.<\/p>\n<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-inheriting\">C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization<\/a><\/h3>\n<p>If you can reuse constructors of the base class in the derived class, do it. You violate the DRY (Don&#8217;t Repeat Yourself) principle if you don&#8217;t do it.<\/p>\n<div style=\"background: #f0f3f3 none repeat scroll 0% 0%; overflow: auto; width: auto; border-width: 0.1em 0.1em 0.1em 0.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;\">Rec<\/span> {\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ... data and lots of nice constructors ...<\/span>\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Oper<\/span> <span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Rec {\r\n    <span style=\"color: #006699; font-weight: bold;\">using<\/span> Rec<span style=\"color: #555555;\">::<\/span>Rec;\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ... no data members ...<\/span>\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ... lots of nice utility functions ...<\/span>\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> Rec2 <span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Rec {\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> x;\r\n    <span style=\"color: #006699; font-weight: bold;\">using<\/span> Rec<span style=\"color: #555555;\">::<\/span>Rec;\r\n};\r\n\r\nRec2 r {<span style=\"color: #cc3300;\">\"foo\"<\/span>, <span style=\"color: #ff6600;\">7<\/span>};\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> val <span style=\"color: #555555;\">=<\/span> r.x;            <span style=\"color: #0099ff; font-style: italic;\">\/\/ uninitialized  (1)<\/span>  \r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>There is a danger in using inheriting constructors. If your derived class, such as <span style=\"font-family: Courier New,Courier,monospace;\">Rec2<\/span> has its own members, they are uninitialized (1).<\/p>\n<h2>Copy and Move<\/h2>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" alignright size-full wp-image-5316\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/movers-24402_1280.png\" alt=\"movers 24402 1280\" width=\"400\" height=\"638\" style=\"float: right;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/movers-24402_1280.png 802w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/movers-24402_1280-188x300.png 188w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/movers-24402_1280-642x1024.png 642w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/09\/movers-24402_1280-768x1226.png 768w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<p>The chapter starts with a meta-rule. Values types, which behave like an int, should be copyable, but interfaces in class hierarchies are not. The last rule C.67 refers to this meta-rule.<\/p>\n<p>Here are the eight rules:<\/p>\n<ul>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-copy-assignment\">C.60: Make copy assignment non-<code class=\"highlighter-rouge no-highlight\">virtual<\/code>, take the parameter by <code class=\"highlighter-rouge no-highlight\">const&amp;<\/code>, and return by non-<code class=\"highlighter-rouge no-highlight\">const&amp;<\/code><\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-copy-semantic\">C.61: A copy operation should copy<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-copy-self\">C.62: Make copy assignment safe for self-assignment<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-move-assignment\">C.63: Make move assignment non-<code class=\"highlighter-rouge no-highlight\">virtual<\/code>, take the parameter by <code class=\"highlighter-rouge no-highlight\">&amp;&amp;<\/code>, and return by non-<code class=\"highlighter-rouge no-highlight\">const&amp;<\/code><\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-move-semantic\">C.64: A move operation should move and leave its source in a valid state<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-move-self\">C.65: Make move assignment safe for self-assignment<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-move-noexcept\">C.66: Make move operations <code class=\"highlighter-rouge no-highlight\">noexcept<\/code><\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-copy-virtual\">C.67: A base class should suppress copying, and provide a virtual <code class=\"highlighter-rouge no-highlight\">clone<\/code> instead, if \u201ccopying\u201d is desired<\/a><\/li>\n<\/ul>\n<p>The first six rules for copy and move consist of 3 similar pairs; therefore, I can explain them together.<\/p>\n<ul>\n<li><b>C.60<\/b> and <b>C.63 <\/b>state that you should make the copy (move) assignment non-virtual and return a non-const reference. There is a difference in the way you should take the parameter.<\/li>\n<\/ul>\n<ul>\n<ul>\n<li>Copy assignment should take its parameter by a <b>const lvalue reference (&amp;)<\/b>&nbsp;because you should not change the source of your assignment<\/li>\n<li>Move assignment should take its parameter by a<b> non-const rvalue reference (&amp;&amp;)<\/b>&nbsp;because you have to modify the source of your assignment<\/li>\n<li>This is the pattern the assignment operators of the standard template library follow. Here is a simplified look at <span style=\"font-family: Courier New,Courier,monospace;\">std::vector.<\/span><\/li>\n<\/ul>\n<\/ul>\n<blockquote>\n<blockquote>\n<div style=\"background: #f0f3f3 none repeat scroll 0% 0%; overflow: auto; width: auto; border-width: 0.1em 0.1em 0.1em 0.8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\">vector<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> vector<span style=\"color: #555555;\">&amp;<\/span> other ); \t\r\nvector<span style=\"color: #555555;\">&amp;<\/span> <span style=\"color: #006699; font-weight: bold;\">operator<\/span><span style=\"color: #555555;\">=<\/span>( vector<span style=\"color: #555555;\">&amp;&amp;<\/span> other );          <span style=\"color: #0099ff; font-style: italic;\">\/\/ (since C++11, until C++17)<\/span>\r\nvector<span style=\"color: #555555;\">&amp;<\/span> <span style=\"color: #006699; font-weight: bold;\">operator<\/span><span style=\"color: #555555;\">=<\/span>( vector<span style=\"color: #555555;\">&amp;&amp;<\/span> other ) noexcept  <span style=\"color: #0099ff; font-style: italic;\">\/\/ since C++17)<br \/><\/span><\/pre>\n<\/div>\n<\/blockquote>\n<\/blockquote>\n<ul>\n<li><strong>C.61<\/strong> and <strong>C.64<\/strong> say a copy (move) operation should copy (move). This is the expected semantic for a = b.<\/li>\n<\/ul>\n<blockquote>\n<ul>\n<li>In case of copying, this means that after copying&nbsp; a and b (a = b) a must be the same: (a ==b).<\/li>\n<li>Copying can be a deep or shallow. Deep copying means that both objects a and b are afterwards totally independent of each other (<a href=\"https:\/\/isocpp.org\/wiki\/faq\/value-vs-ref-semantics\">value semantic<\/a>). Shallow copying means that both objects a and b share an object afterwards (<a href=\"https:\/\/isocpp.org\/wiki\/faq\/value-vs-ref-semantics\">reference semantic<\/a>).<\/li>\n<li>C.64 states the moved-from object should be in a valid state. Most of the times this is the default state of the source. The C++ standard requires, that the moved-from object must be afterwards in an unspecified but valid state.<\/li>\n<\/ul>\n<\/blockquote>\n<ul>\n<li><b>C.62<\/b> and <b>C.65 <\/b>state the same. Copy (move) assignment should be safe for self-assignment. x = x should not change the value of x.\n<ul>\n<li>Copy (move) assignment of the containers of the STL, <span style=\"font-family: Courier New,Courier,monospace;\">std::string<\/span>, and built-in type such as <span style=\"font-family: Courier New,Courier,monospace;\">int<\/span> is safe for self-assignment; therefore, the default generated copy (move) assignment operator is, in this case, safe for self-assignment. The same will hold for an automatically generated copy (move) assignment operator, which uses types that are safe for self-assignment.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<blockquote>\n<blockquote>\n<div style=\"background: #f0f3f3 none repeat scroll 0% 0%; overflow: auto; width: auto; border-width: 0.1em 0.1em 0.1em 0.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;\">Foo<\/span> {\r\n    string s;\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> i;\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n  Foo<span style=\"color: #555555;\">&amp;<\/span> Foo<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> Foo<span style=\"color: #555555;\">&amp;<\/span> a){\r\n    s <span style=\"color: #555555;\">=<\/span> a.s;\r\n    i <span style=\"color: #555555;\">=<\/span> a.i;\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  Foo<span style=\"color: #555555;\">&amp;<\/span> Foo<span style=\"color: #555555;\">::<\/span><span style=\"color: #006699; font-weight: bold;\">operator<\/span><span style=\"color: #555555;\">=<\/span>(Foo<span style=\"color: #555555;\">&amp;&amp;<\/span> a) noexcept {\r\n    s <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>move(a.s);\r\n    i <span style=\"color: #555555;\">=<\/span> a.i;\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>;<br \/>&nbsp; }<br \/>  \/\/ ....<br \/>};<\/pre>\n<\/div>\n<p><strong><br \/> <\/strong>The code snippet shows that there is no test for self-assignment such as in the next example necessa<b>r<\/b>y. Here is the version of the type <span style=\"font-family: Courier New,Courier,monospace;\">Foo<\/span> with redundant (expensive) checks (1) and (2) for self-assignment.<strong><br \/> <\/strong><\/p><\/blockquote>\n<blockquote>\n<div style=\"background: #f0f3f3 none repeat scroll 0% 0%; overflow: auto; width: auto; border-width: 0.1em 0.1em 0.1em 0.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;\">Foo<\/span> {\r\n    string s;\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> i;\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n  Foo<span style=\"color: #555555;\">&amp;<\/span> Foo<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> Foo<span style=\"color: #555555;\">&amp;<\/span> a){\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (<span style=\"color: #006699; font-weight: bold;\">this<\/span> <span style=\"color: #555555;\">==<\/span> <span style=\"color: #555555;\">&amp;<\/span>a) <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>;          <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n    s <span style=\"color: #555555;\">=<\/span> a.s;\r\n    i <span style=\"color: #555555;\">=<\/span> a.i;\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  Foo<span style=\"color: #555555;\">&amp;<\/span> Foo<span style=\"color: #555555;\">::<\/span><span style=\"color: #006699; font-weight: bold;\">operator<\/span><span style=\"color: #555555;\">=<\/span>(Foo<span style=\"color: #555555;\">&amp;&amp;<\/span> a) noexcept {   <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">if<\/span> (<span style=\"color: #006699; font-weight: bold;\">this<\/span> <span style=\"color: #555555;\">==<\/span> <span style=\"color: #555555;\">&amp;<\/span>a) <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    s <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>move(a.s);\r\n    i <span style=\"color: #555555;\">=<\/span> a.i;\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  <span style=\"color: #0099ff; font-style: italic;\">\/\/ ....<\/span>\r\n};<\/pre>\n<\/div>\n<\/blockquote>\n<\/blockquote>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-move-noexcept\">C.66: Make move operations <code class=\"highlighter-rouge no-highlight\">noexcept<\/code><\/a><\/h3>\n<p>M<a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-move-noexcept\"><code class=\"highlighter-rouge no-highlight\"><\/code><\/a>ove operations should not throw; therefore, you should declare them as <span style=\"font-family: courier new,courier;\">noexcept. <\/span>You can implement your move constructor and move assignment operators that do not throw. <span style=\"font-family: courier new,courier;\"><br \/><\/span><\/p>\n<p>This is the pattern the move operators of the standard template library follow. Have a look at <span style=\"font-family: Courier New,Courier,monospace;\">std::vector.<\/span><\/p>\n<div style=\"background: #f0f3f3 none repeat scroll 0% 0%; overflow: auto; width: auto; border-width: 0.1em 0.1em 0.1em 0.8em;\">\n<pre style=\"margin: 0px; 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: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Vector<\/span> {\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n    Vector(Vector<span style=\"color: #555555;\">&amp;&amp;<\/span> a) noexcept <span style=\"color: #555555;\">:<\/span>elem{a.elem}, sz{a.sz} { a.sz <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>; a.elem <span style=\"color: #555555;\">=<\/span> nullptr; }\r\n    Vector<span style=\"color: #555555;\">&amp;<\/span> <span style=\"color: #006699; font-weight: bold;\">operator<\/span><span style=\"color: #555555;\">=<\/span>(Vector<span style=\"color: #555555;\">&amp;&amp;<\/span> a) noexcept { elem <span style=\"color: #555555;\">=<\/span> a.elem; sz <span style=\"color: #555555;\">=<\/span> a.sz; a.sz <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>; a.elem <span style=\"color: #555555;\">=<\/span> nullptr; }\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    T<span style=\"color: #555555;\">*<\/span> elem;\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> sz;\r\n};<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The last rule C.67 deserves more attention.<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-copy-virtual\">C.67: A base class should suppress copying, and provide a virtual <code class=\"highlighter-rouge no-highlight\">clone<\/code> instead, if \u201ccopying\u201d is desired<\/a><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rc-copy-virtual\"> <code class=\"highlighter-rouge no-highlight\"><\/code><\/a><\/h3>\n<p>The main reason for this rule is that slicing is not possible. Slicing is one of these phenomena in C++, and my colleagues always warned me. There also exists an article on Wikipedia about <a href=\"https:\/\/en.wikipedia.org\/wiki\/Object_slicing\">object slicing<\/a>.<\/p>\n<p>Slicing will happen when an object of a derived class is copied to an object of a base class.<\/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;\">struct<\/span> Base { <span style=\"color: #007788; font-weight: bold;\">int<\/span> base_; };\r\n \r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> Derived <span style=\"color: #555555;\">:<\/span> Base { <span style=\"color: #007788; font-weight: bold;\">int<\/span> derived_; };\r\n \r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n  Derived d;\r\n  Base b <span style=\"color: #555555;\">=<\/span> d;   <span style=\"color: #0099ff; font-style: italic;\">\/\/ slicing, only the Base parts of (base_) are copied<\/span>\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>In this scenario, the copy operations of the base class are used; therefore, only the base part of <span style=\"font-family: courier new,courier;\">d<\/span> is copied.<\/p>\n<p>From the object-oriented perspective, an instance of <span style=\"font-family: courier new,courier;\">Derived<\/span> <a href=\"https:\/\/en.wikipedia.org\/wiki\/Is-a\">is-a<\/a> an instance of <span style=\"font-family: courier new,courier;\">Base.<\/span> That means whenever you need an instance of Base you can use an instance of Derived. But you have to be careful. If you take the instance of <span style=\"font-family: courier new,courier;\">Base<\/span> by copy (value-semantic), you will only get the base parts of an instance of <span style=\"font-family: courier new,courier;\">Derived.<\/span><\/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: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">needBase<\/span>(Base b){ .... };\r\n\r\nDerived der;\r\nneedBase(der);      <span style=\"color: #0099ff; font-style: italic;\">\/\/ slicing kicks in<\/span>\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The cure that the guidelines suggest is that the base class should suppress copying but provide a virtual clone member function if copying is desired. Here is an example from the guidelines.<\/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;\">B<\/span> { <span style=\"color: #0099ff; font-style: italic;\">\/\/ GOOD: base class suppresses copying<\/span>\r\n    B(<span style=\"color: #006699; font-weight: bold;\">const<\/span> B<span style=\"color: #555555;\">&amp;<\/span>) <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">delete<\/span>;\r\n    B<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> B<span style=\"color: #555555;\">&amp;<\/span>) <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">delete<\/span>;\r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> unique_ptr<span style=\"color: #555555;\">&lt;<\/span>B<span style=\"color: #555555;\">&gt;<\/span> clone() { <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #0099ff; font-style: italic;\">\/* B object *\/<\/span>; }\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">D<\/span> <span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> B {\r\n    string more_data; <span style=\"color: #0099ff; font-style: italic;\">\/\/ add a data member<\/span>\r\n    unique_ptr<span style=\"color: #555555;\">&lt;<\/span>B<span style=\"color: #555555;\">&gt;<\/span> clone() override { <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #0099ff; font-style: italic;\">\/* D object *\/<\/span>; }\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">auto<\/span> d <span style=\"color: #555555;\">=<\/span> make_unique<span style=\"color: #555555;\">&lt;<\/span>D<span style=\"color: #555555;\">&gt;<\/span>();\r\n<span style=\"color: #006699; font-weight: bold;\">auto<\/span> b <span style=\"color: #555555;\">=<\/span> d.clone(); <span style=\"color: #0099ff; font-style: italic;\">\/\/ ok, deep clone<\/span>\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The <span style=\"font-family: courier new,courier;\">clone<\/span> method returns the newly created object in a <span style=\"font-family: courier new,courier;\">std::unique_ptr;<\/span> therefore, the ownership goes to the caller. Such a <span style=\"font-family: courier new,courier;\">clone<\/span> method is better known as a factory method. A factory method is one of the creational patterns from the book:&nbsp;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Design_Patterns\">Design Pattern: Elements of Reusable Object-Oriented Software. <\/a><\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>There are a few rules for default operations left. The <a href=\"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-comparison-swap-and-hash\">next post<\/a> deals with comparisons, <span style=\"font-family: courier new,courier;\">swap,<\/span> and <span style=\"font-family: courier new,courier;\">hash.<\/span><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The rules for copy and move are pretty obvious. But before I describe them I have to write about the two remaining rules for constructors. They are about delegating and inheriting constructors.<\/p>\n","protected":false},"author":21,"featured_media":5311,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[372],"tags":[499,417],"class_list":["post-5317","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-modern-c","tag-classes","tag-rule-of-zero-six"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5317","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=5317"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5317\/revisions"}],"predecessor-version":[{"id":6860,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5317\/revisions\/6860"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5311"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5317"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5317"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5317"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}