简体   繁体   English

复制对象(无堆)

[英]Copying Objects(Without Heap)

Consider the following piece of code考虑下面的一段代码

class A{
  public:
     int val;
     a(); 
}
int main(){
     A obj1;
     A obj2=obj1;
}

In this case, there are no pointers or heap involved.在这种情况下,不涉及指针或堆。 Will this A obj2=obj1 be shallow copy or deep copy?这个A obj2=obj1是浅拷贝还是深拷贝? When I use addressof() function on obj1 and obj2 I get different values.当我在 obj1 和 obj2 上使用 addressof() 函数时,我得到不同的值。

There's actually no such thing as a shallow copy here, because copying an object of type A will always copy val .这里实际上没有浅拷贝这样的东西,因为复制A类型的对象将始终复制val

But with a class like this:但是对于这样的类:

class B
{
    char *s;
};

you can make either a shallow copy or a deep copy, depending on whether you copy just the pointer s (shallow), or whether a copy is made of what s is pointing to (deep).您可以制作浅拷贝或深拷贝,这取决于您是只拷贝指针s (浅),还是拷贝s指向的内容(深)。 In the case of a deep copy, the value of s is different in the copy, of course, because it ends up pointing at a different chunk of memory to the original.在深拷贝的情况下, s的值在拷贝中是不同的,当然,因为它最终指向与原始内存不同的内存块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM