使用指针的C ++复制构造函数 [英] C++ copy constructor using pointers

查看:190
本文介绍了使用指针的C ++复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以在此C ++代码中解释*p=*q的含义吗?这是复制构造函数的概念吗?

Can anyone explain the meaning of *p=*q in this C++ code? Is this a copy constructor concept?

class A{
  //any code
}

int main(){
  A *p=new A();
  A *q=new A();
  *p=*q;
  return 0;
}

推荐答案

这是复制构造函数的概念吗?

Is this a copy constructor concept?

不,您指的是副本分配概念.考虑一下:

No, what you are referring to is a copy assignment concept. Consider this:

int* p = new int{9};
int* q = new int{10};
*p = *q;

如上所示,仅复制指向的变量q的值.这等效于对象的副本分配.如果您要这样做:

As you can see above, only the value of the variable q which is pointed to is copied. This is the equivalent of the copy assignment for objects. If you were to do this:

p = q;

这将不是副本分配,因为两个int都指向相同的地址和值,这意味着对pq的任何更改都将反映在另一个变量上. 为了给出一个更具体且经过验证的示例,下面是一些代码:

Then this would not be a copy assignment, because both int's point to the same address and value, meaning any change to p or q would be reflected on the other variable. To give a more concrete and validated example, here is some code:

int main() 
{
    int* p = new int{9};
    int* q = new int{10};
    *p = *q;
    //p = 10, q = 10
    *p = 11;
    //p = 11, q = 10
    delete p;
    delete q;
}

这是一个补充的反例

int main() 
{
    int* p = new int{9};
    int* q = new int{10};
    p = q;
    //p = 10, q = 10
    *p = 11;
    //p = 11, q = 11
    delete p;
    //delete q; Not needed because p and q point to same int
}

如您所见,更改反映在p=q

As you can see, the changes are reflected on both variables for p=q

旁注 您提到了复制构造,但是您对该概念不清楚.这就是复制构造的样子:

Side Note You mentioned copy-construction, but you were unclear about the concept. Here is what copy-construction would have looked like:

int* p = new int{9};
int* q = new int{*p}; //q=9

复制构造与复制分配的区别在于,使用复制构造时,变量没有值,并且对于对象,尚未调用构造函数.混淆这两个术语是很常见的,但是根本的区别使这两个概念完全不同.

Copy construction differs from copy assignment in the sense that with copy construction, the variable doesn't already have a value, and for an object, the constructor has yet to be called. Mixing up the 2 terms is common, but the fundamental differences make the two concepts, well, different.

这篇关于使用指针的C ++复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆