Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Shallow copy:</strong></p> <p>Some members of the copy may reference the same objects as the original:</p> <pre><code>class X { private: int i; int *pi; public: X() : pi(new int) { } X(const X&amp; copy) // &lt;-- copy ctor : i(copy.i), pi(copy.pi) { } }; </code></pre> <p>Here, the <code>pi</code> member of the original and copied <code>X</code> object will both point to the same <code>int</code>.</p> <hr> <p><strong>Deep copy:</strong></p> <p>All members of the original are cloned (recursively, if necessary). There are no shared objects:</p> <pre><code>class X { private: int i; int *pi; public: X() : pi(new int) { } X(const X&amp; copy) // &lt;-- copy ctor : i(copy.i), pi(new int(*copy.pi)) // &lt;-- note this line in particular! { } }; </code></pre> <p>Here, the <code>pi</code> member of the original and copied <code>X</code> object will point to different <code>int</code> objects, but both of these have the same value.</p> <hr> <p><strike><sub>The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.</sub></strike></p> <blockquote> <p><strong>Correction:</strong> Several comments below have correctly pointed out that it is wrong to say that the default copy constructor <em>always</em> performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, <strong>or something in-between the two</strong>, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.</p> </blockquote> <p>Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:</p> <blockquote> <p><em>The implicitly defined copy constructor for class <code>X</code> performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.</em></p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload