C++ - Shallow copying a pointer. Why is this code working?
<p>To my understanding of the subject:
A shallow copy is when the non-pointer types of an object are copied to another object. Shallow copies can't be done when an object has pointers because, the object being copied will get the  address of that pointer, and when either of the two objects are deleted, the other will be left dangling  since they were pointing to the same location in memory.
A deep copy is used when pointers are involved because it reserves a space separate from the original object's space and just copies the contents from one memory location to another. This way, when one of the objects is deleted, teh other isn't left dangling.
That said, I would like to know why this program is working even though I've done a shallow copy of a pointer</p>

<pre><code>struct aStruct {
    int *i;
    aStruct(int *p) : i(p) {
        cout &lt;&lt; "Created aStruct" &lt;&lt; endl;
    }
    aStruct(const aStruct &amp;s) {
        cout &lt;&lt; "Copying aStruct" &lt;&lt; endl;
        i = s.i;
    }
    aStruct &amp;operator=(const aStruct &amp;s) {
        cout &lt;&lt; "Assigning aStruct" &lt;&lt; endl;
        i = s.i;
        return *this;
    }
};

int main() {
    int *x = new int(3);
    aStruct s1(x);
    aStruct s2 = s1;
    int *y = new int(4);
    aStruct s3(y);
    s3 = s1;
}
</code></pre>

<p>s1, s2, and s3 all have their variable i pointing to the same place. So when the end of the main() function is reached and one of them is destroyed, shouldn't the others be left dangling causing an error? My program works fine. Could someone please be kind enough to explain this to me?</p>

<p>Thanks all</p>