Shallow copying a pointer. Why is this code working?

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

struct aStruct {
    int *i;
    aStruct(int *p) : i(p) {
        cout << "Created aStruct" << endl;
    }
    aStruct(const aStruct &s) {
        cout << "Copying aStruct" << endl;
        i = s.i;
    }
    aStruct &operator=(const aStruct &s) {
        cout << "Assigning aStruct" << 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;
}

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?

Thanks all


You are copying the pointer, not the data. Each object here is an object in its own right, additionally, you seem to be under the impression that C++ is garbage-collected. it is not (except in some uncommon implementations)

Your program basically leaks memory and is only cleaned up by virtue of the OS releasing whatever your process consumed after it terminated. Consequently, all your pointers are pointing to perfectly valid memory throughout the lifetime of your application.


Unfortunately, there is no concept of Deep and Shallow pointers in C++. The notion of references in Java and C# is different from pointers in C++. You should read on

  • What are the differences between a pointer variable and a reference variable in C++?
  • What is a smart pointer and when should I use one?
  • What is The Rule of Three?
  • Take it this way, in C++, Pointers refers to whatever object is in the memory location it, the pointer is pointing to.

    So, what you are doing is copying the allocated location into your constructor into the object... When the destructor runs, of cause the entire object is freed from memory (dead), including the pointer int* i that is a data member. But the memory location allocated by new isn't freed until someone calls that same location with a delete .

    链接地址: http://www.djcxy.com/p/79376.html

    上一篇: 在处理int和str时无法理解python浅层副本

    下一篇: 浅拷贝指针。 为什么这个代码有效?