{"id":6447,"date":"2022-09-12T12:54:15","date_gmt":"2022-09-12T12:54:15","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/factory-method-2\/"},"modified":"2023-06-26T09:00:25","modified_gmt":"2023-06-26T09:00:25","slug":"factory-method-2","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/factory-method-2\/","title":{"rendered":"The Factory Method (Slicing and Ownership Semantics)"},"content":{"rendered":"<p>In the last installment of this blog, I introduced the Factory Method: Creational Patterns: Factory Method 1. My implementation had two serious issues: slicing and ownership semantics. Today, I fix these issues.<\/p>\n<p><!--more--><\/p>\n<h3><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6435\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/CreationalPatterns.png\" alt=\"CreationalPatterns\" width=\"650\" height=\"330\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/CreationalPatterns.png 1220w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/CreationalPatterns-300x152.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/CreationalPatterns-1024x520.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/CreationalPatterns-768x390.png 768w\" sizes=\"auto, (max-width: 650px) 100vw, 650px\" \/><\/h3>\n<p>To remind you, here is a simplified and slightly modified implementation of the Factory Method in my last post. First, this implementation support only the member function <code>clone<\/code>; second, also the base class <code>Window<\/code> should be cloneable.<\/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: #0099ff; font-style: italic;\">\/\/ factoryMethodWindowIssues.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ Product<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Window<\/span>{ \r\n <span style=\"color: #006699; font-weight: bold;\">public<\/span><span style=\"color: #555555;\">:<\/span>                \r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> Window<span style=\"color: #555555;\">*<\/span> clone() { \r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Clone Window\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> <span style=\"color: #cc00ff;\">Window<\/span>(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>);\r\n    }                       \r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #555555;\">~<\/span>Window() {};\r\n};\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ Concrete Products <\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">DefaultWindow<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Window { \r\n     DefaultWindow<span style=\"color: #555555;\">*<\/span> clone() override { \r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Clone DefaultWindow\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> <span style=\"color: #cc00ff;\">DefaultWindow<\/span>(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>);\r\n    } \r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">FancyWindow<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Window { \r\n    FancyWindow<span style=\"color: #555555;\">*<\/span> clone() override { \r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Clone FancyWindow\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> <span style=\"color: #cc00ff;\">FancyWindow<\/span>(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>);\r\n    } \r\n};\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ Concrete Creator or Client                             <\/span>\r\nWindow<span style=\"color: #555555;\">*<\/span> <span style=\"color: #cc00ff;\">cloneWindow<\/span>(Window<span style=\"color: #555555;\">&amp;<\/span> oldWindow) {                    \r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> oldWindow.clone();\r\n}\r\n  \r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>() {\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n\r\n    Window window;\r\n    DefaultWindow defaultWindow;\r\n    FancyWindow fancyWindow;\r\n\r\n    <span style=\"color: #006699; font-weight: bold;\">const<\/span> Window<span style=\"color: #555555;\">*<\/span> window1 <span style=\"color: #555555;\">=<\/span> cloneWindow(window);\r\n    <span style=\"color: #006699; font-weight: bold;\">const<\/span> Window<span style=\"color: #555555;\">*<\/span> defaultWindow1 <span style=\"color: #555555;\">=<\/span> cloneWindow(defaultWindow);\r\n    <span style=\"color: #006699; font-weight: bold;\">const<\/span> Window<span style=\"color: #555555;\">*<\/span> fancyWindow1 <span style=\"color: #555555;\">=<\/span> cloneWindow(fancyWindow);\r\n  \r\n    <span style=\"color: #006699; font-weight: bold;\">delete<\/span> window1;\r\n    <span style=\"color: #006699; font-weight: bold;\">delete<\/span> defaultWindow1;\r\n    <span style=\"color: #006699; font-weight: bold;\">delete<\/span> fancyWindow1;\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n  \r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The program produces the expected polymorphic behavior.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6443\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodWindowIssues.png\" alt=\"factoryMethodWindowIssues\" width=\"441\" height=\"175\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodWindowIssues.png 441w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodWindowIssues-300x119.png 300w\" sizes=\"auto, (max-width: 441px) 100vw, 441px\" \/><\/p>\n<\/p>\n<h3>Slicing<\/h3>\n<p>First: What is slicing?<\/p>\n<ul>\n<li><strong>Slicing<\/strong> means you want to copy an object during assignment or initialization, and you get only a part of the object.<\/li>\n<\/ul>\n<p>Slicing is one of the darkest corners of C++. Let me give you a simple example:<\/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: #0099ff; font-style: italic;\">\/\/ slice.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;typeinfo&gt;<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> Base { };\r\n \r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> Derived <span style=\"color: #555555;\">:<\/span> Base { };\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">displayTypeinfo<\/span>(<span style=\"color: #006699; font-weight: bold;\">const<\/span> Base<span style=\"color: #555555;\">&amp;<\/span> b) {\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #006699; font-weight: bold;\">typeid<\/span>(b).name() <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>; \r\n}\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">needB<\/span>(Base b) {\r\n    displayTypeinfo(b);\r\n};\r\n \r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>() {\r\n\r\n    Derived d;\r\n  \r\n    Base b <span style=\"color: #555555;\">=<\/span> d;          \r\n    displayTypeinfo(b);      <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n  \r\n    Base b2(d);        \r\n    displayTypeinfo(b2);     <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n  \r\n    needB(d);                <span style=\"color: #0099ff; font-style: italic;\">\/\/ (3)<\/span>\r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The expressions (1), (2), and (3) have all the same effect: The <code>Derived<\/code> part of <code>d<\/code> is removed. I assume that was not your intention.<\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5209\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/03\/slice.png\" alt=\"slice\" width=\"300\" height=\"121\" style=\"display: block; margin-left: auto; margin-right: auto;\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>You may ask yourself. Why is slicing an issue for the example<span style=\"color: #000000; font-family: courier new, courier;\"> factoryMethodWindowIssues.cpp.<\/span> Let me quote the C++ Core Guidelines: <a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#c67-a-polymorphic-class-should-suppress-public-copymove\">C.67: A polymorphic class should suppress public copy\/move<\/a>.<\/p>\n<p>Okay, there is a new question:&nbsp; What is a polymorphic class?<\/p>\n<ul>\n<li>A <strong>polymorphic class<\/strong> is a class that defines or inherits at least one virtual function.<\/li>\n<\/ul>\n<p>Here is the issue. <code>Window<\/code> in the program <span style=\"color: #000000; font-family: courier new, courier;\">factoryMethodWindowIssues.cpp<\/span> is a polymorphic class, and it does not suppress public copy\/move. A <code>Window<\/code> can be a victim of slicing. The following program exemplifies this. I just removed the reference from the function signature of the function <code>cloneWindow<\/code>:<\/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: #0099ff; font-style: italic;\">\/\/ Concrete Creator or Client                             <\/span>\r\nWindow<span style=\"color: #555555;\">*<\/span> <span style=\"color: #cc00ff;\">cloneWindow<\/span>(Window oldWindow) {                    \r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> oldWindow.clone();\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Due to the fact that the factory function <code>cloneWindow<\/code> takes its argument by copy and not by reference anymore, slicing kicks in.<\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6444\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodWindowIssuesSlicing.png\" alt=\"factoryMethodWindowIssuesSlicing\" width=\"400\" height=\"146\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodWindowIssuesSlicing.png 472w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodWindowIssuesSlicing-300x109.png 300w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<p>Let&#8217;s see what happens when I follow rule&nbsp; <a href=\"https:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#c67-a-polymorphic-class-should-suppress-public-copymove\">C.67: A polymorphic class should suppress public copy\/move<\/a>.<\/p>\n<p>Here is the fixed program:<\/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: #0099ff; font-style: italic;\">\/\/ factoryMethodWindowSlicingFixed.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ Product<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Window<\/span>{ \r\n <span style=\"color: #006699; font-weight: bold;\">public<\/span><span style=\"color: #555555;\">:<\/span>      \r\n    Window() <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">default<\/span>;                          <span style=\"color: #0099ff; font-style: italic;\">\/\/ (3)<\/span>\r\n    Window(<span style=\"color: #006699; font-weight: bold;\">const<\/span> Window<span style=\"color: #555555;\">&amp;<\/span>) <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">delete<\/span>;              <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n    Window<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> Window<span style=\"color: #555555;\">&amp;<\/span>) <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">delete<\/span>; <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> Window<span style=\"color: #555555;\">*<\/span> <span style=\"color: #cc00ff;\">clone<\/span>() { \r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Clone Window\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> Window(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>);\r\n    }                       \r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #555555;\">~<\/span>Window() {};\r\n};\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ Concrete Products <\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">DefaultWindow<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Window { \r\n     DefaultWindow<span style=\"color: #555555;\">*<\/span> clone() override { \r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Clone DefaultWindow\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> <span style=\"color: #cc00ff;\">DefaultWindow<\/span>(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>);\r\n    } \r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">FancyWindow<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Window { \r\n    FancyWindow<span style=\"color: #555555;\">*<\/span> clone() override { \r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Clone FancyWindow\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> <span style=\"color: #cc00ff;\">FancyWindow<\/span>(<span style=\"color: #555555;\">*<\/span><span style=\"color: #006699; font-weight: bold;\">this<\/span>);\r\n    } \r\n};\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ Concrete Creator or Client                             <\/span>\r\nWindow<span style=\"color: #555555;\">*<\/span> <span style=\"color: #cc00ff;\">cloneWindow<\/span>(Window oldWindow) {           <span style=\"color: #0099ff; font-style: italic;\">\/\/ (4)                 <\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> oldWindow.clone();\r\n}\r\n  \r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>() {\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n\r\n    Window window;\r\n    DefaultWindow defaultWindow;\r\n    FancyWindow fancyWindow;\r\n\r\n    <span style=\"color: #006699; font-weight: bold;\">const<\/span> Window<span style=\"color: #555555;\">*<\/span> window1 <span style=\"color: #555555;\">=<\/span> cloneWindow(window);\r\n    <span style=\"color: #006699; font-weight: bold;\">const<\/span> Window<span style=\"color: #555555;\">*<\/span> defaultWindow1 <span style=\"color: #555555;\">=<\/span> cloneWindow(defaultWindow);\r\n    <span style=\"color: #006699; font-weight: bold;\">const<\/span> Window<span style=\"color: #555555;\">*<\/span> fancyWindow1 <span style=\"color: #555555;\">=<\/span> cloneWindow(fancyWindow);\r\n  \r\n    <span style=\"color: #006699; font-weight: bold;\">delete<\/span> window1;\r\n    <span style=\"color: #006699; font-weight: bold;\">delete<\/span> defaultWindow1;\r\n    <span style=\"color: #006699; font-weight: bold;\">delete<\/span> fancyWindow1;\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n  \r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>I deleted the copy constructor (line 1) and copy assignment operator (line 2). Due to the declared copy constructor, the class <code>Window<\/code> supports no move semantics. Additionally, the default constructor is also not declared. Therefore, I have to default it (line 1).<\/p>\n<p>The error message of the Microsoft Visual C++ compiler comes directly to the point:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6445\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodWindowsSlicingFixed.png\" alt=\"factoryMethodWindowsSlicingFixed\" width=\"650\" height=\"192\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodWindowsSlicingFixed.png 1241w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodWindowsSlicingFixed-300x89.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodWindowsSlicingFixed-1024x303.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodWindowsSlicingFixed-768x227.png 768w\" sizes=\"auto, (max-width: 650px) 100vw, 650px\" \/><\/p>\n<p>The necessary copy constructor is deleted.<\/p>\n<p>Okay. Let me write about the ownership issue of the program.<\/p>\n<h3>Ownership Semantics<\/h3>\n<p>In general, you don&#8217;t know the implementation of the factory function <code>cloneWindow<\/code>. <code>cloneWindow<\/code> returns a pointer to <code>Window<\/code>. <strong>Pointers have, by design, a flaw. They model two completely different semantics: ownership and borrowing.<\/strong><\/p>\n<ul>\n<li><strong>Ownership<\/strong>: the caller is responsible for the Windows and must destroy it; this is the behavior that program <code>factoryMethodWindowsIssues.cpp<\/code> modeled<\/li>\n<li><strong>Borrowing<\/strong>: the callee is responsible for the Window and borrows it from the caller<\/li>\n<\/ul>\n<p>Let me emphasize this one more.<\/p>\n<ul>\n<li><strong>Owner<\/strong>: You are the owner of the <code>Window<\/code>. You have to take care of it and destroy it. If not, you have a memory leak.<\/li>\n<li><strong>Borrower<\/strong>: You are not the owner of the Window. You can not destroy it. If you destroy it, you have a double delete.<\/li>\n<\/ul>\n<p>How can we overcome this design flaw? The rescue has two parts. A weak one based on discipline and a strong one based on the type system.<\/p>\n<h4>The Weak Rescue<\/h4>\n<p>The weak rescue is based on discipline: In modern C++, we don&#8217;t transfer ownership with a raw pointer.<\/p>\n<h4>The Strong Rescue<\/h4>\n<p>The strong rescue is based on the type system. When you want to transfer ownership, use a smart pointer. You have two choices:<\/p>\n<ul>\n<li><code>std::unique_ptr&lt;Window&gt;<\/code>: Returning a <code>std::unique_ptr&lt;Window&gt;<\/code> means that the caller is the owner. The <code>std::unique_ptr&lt;Window&gt;<\/code> behaves such as a local. When it goes out of scope, it is automatically destroyed.<\/li>\n<li><code>std::shared_ptr&lt;Window&gt;<\/code>: Returning a <code>std::shared_ptr&lt;Window&gt;<\/code> means that the caller and the called share ownership. When neither the caller nor the callee needs the <code>std::shared_ptr&lt;Window&gt;<\/code> anymore, it is automatically destroyed.<\/li>\n<\/ul>\n<p>The following program <code>factoryMethodUniquePtr.cpp<\/code> uses a <code>std::unique_ptr&lt;Window&gt;<\/code> to explicitly transfer ownership. Additionally, a<code> std::unique_ptr&nbsp;<\/code>can not be copied. Consequentially, the factory function creates a new <code>std::unique_ptr&lt;Window&gt;<\/code>.<\/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: #009999;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ factoryMethodUniquePtr.cpp<\/span><br \/><br \/>#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;memory&gt;<\/span>\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ Product<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Window<\/span>{ \r\n <span style=\"color: #006699; font-weight: bold;\">public<\/span><span style=\"color: #555555;\">:<\/span> \r\n    <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> std<span style=\"color: #555555;\">::<\/span>unique_ptr<span style=\"color: #555555;\">&lt;<\/span>Window<span style=\"color: #555555;\">&gt;<\/span> create() { \r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Create Window\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> std<span style=\"color: #555555;\">::<\/span>make_unique<span style=\"color: #555555;\">&lt;<\/span>Window<span style=\"color: #555555;\">&gt;<\/span>();\r\n    } \r\n};\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ Concrete Products <\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">DefaultWindow<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Window {\r\n    std<span style=\"color: #555555;\">::<\/span>unique_ptr<span style=\"color: #555555;\">&lt;<\/span>Window<span style=\"color: #555555;\">&gt;<\/span> create() override { \r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Create DefaultWindow\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> std<span style=\"color: #555555;\">::<\/span>make_unique<span style=\"color: #555555;\">&lt;<\/span>DefaultWindow<span style=\"color: #555555;\">&gt;<\/span>();\r\n    } \r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">FancyWindow<\/span><span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Window {\r\n    std<span style=\"color: #555555;\">::<\/span>unique_ptr<span style=\"color: #555555;\">&lt;<\/span>Window<span style=\"color: #555555;\">&gt;<\/span> create() override { \r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Create FancyWindow\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n        <span style=\"color: #006699; font-weight: bold;\">return<\/span> std<span style=\"color: #555555;\">::<\/span>make_unique<span style=\"color: #555555;\">&lt;<\/span>FancyWindow<span style=\"color: #555555;\">&gt;<\/span>();\r\n    } \r\n};\r\n\r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ Concrete Creator or Client<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">auto<\/span> <span style=\"color: #cc00ff;\">createWindow<\/span>(std<span style=\"color: #555555;\">::<\/span>unique_ptr<span style=\"color: #555555;\">&lt;<\/span>Window<span style=\"color: #555555;\">&gt;&amp;<\/span> oldWindow) { \r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> oldWindow<span style=\"color: #555555;\">-&gt;<\/span>create();\r\n}\r\n  \r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>() {\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>unique_ptr<span style=\"color: #555555;\">&lt;<\/span>Window<span style=\"color: #555555;\">&gt;<\/span> window <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>make_unique<span style=\"color: #555555;\">&lt;<\/span>Window<span style=\"color: #555555;\">&gt;<\/span>();\r\n    std<span style=\"color: #555555;\">::<\/span>unique_ptr<span style=\"color: #555555;\">&lt;<\/span>Window<span style=\"color: #555555;\">&gt;<\/span> defaultWindow <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>make_unique<span style=\"color: #555555;\">&lt;<\/span>DefaultWindow<span style=\"color: #555555;\">&gt;<\/span>();\r\n    std<span style=\"color: #555555;\">::<\/span>unique_ptr<span style=\"color: #555555;\">&lt;<\/span>Window<span style=\"color: #555555;\">&gt;<\/span> fancyWindow <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>make_unique<span style=\"color: #555555;\">&lt;<\/span>FancyWindow<span style=\"color: #555555;\">&gt;<\/span>();\r\n  \r\n    <span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #006699; font-weight: bold;\">auto<\/span> window1 <span style=\"color: #555555;\">=<\/span> createWindow(window);\r\n    <span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #006699; font-weight: bold;\">auto<\/span> defaultWindow1 <span style=\"color: #555555;\">=<\/span> createWindow(defaultWindow);\r\n    <span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #006699; font-weight: bold;\">auto<\/span> fancyWindow1 <span style=\"color: #555555;\">=<\/span> createWindow(fancyWindow);\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n  \r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Finally, here is the output of the program.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6446\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodUniquePtr.png\" alt=\"factoryMethodUniquePtr\" width=\"463\" height=\"173\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodUniquePtr.png 463w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/factoryMethodUniquePtr-300x112.png 300w\" sizes=\"auto, (max-width: 463px) 100vw, 463px\" \/><\/p>\n<p>Each <code>create<\/code> member function returns a <code>std::unique_ptr&lt;Window&gt;<\/code>, but creates under the hood a <code>std::unique_ptr&lt;Window&gt;<\/code>, a <code>std::unique_ptr&lt;DefaultWindow&gt;<\/code>, or a <code>std::unique_ptr&lt;FancyWindow&gt;<\/code>. Therefore, the polymorphic behavior of the <code>createWindow<\/code> function is preserved.<\/p>\n<p>Additionally, this implementation based on<code> std::unique_ptr<\/code> solves the slicing issue because a <code>std::unique_ptr&lt;Window&gt;<\/code> cannot be copied.<\/p>\n<h2>What&#8217;s Next?<\/h2>\n<p>The final program <code>factoryMethodUniquePtr.cpp<\/code> is fine. It overcomes the slicing and ownership issues. Let me elaborate in my next post on the most controversial pattern of the Design Patterns book: the Singleton pattern.<\/p>\n<p>&nbsp;<\/p>\n<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the last installment of this blog, I introduced the Factory Method: Creational Patterns: Factory Method 1. My implementation had two serious issues: slicing and ownership semantics. Today, I fix these issues.<\/p>\n","protected":false},"author":21,"featured_media":6435,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[379],"tags":[407,408],"class_list":["post-6447","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-patterns","tag-ownership","tag-slicing"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6447","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=6447"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6447\/revisions"}],"predecessor-version":[{"id":6660,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6447\/revisions\/6660"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/6435"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=6447"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=6447"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=6447"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}