温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++中怎么实现对象的拷贝与赋值操作

发布时间:2021-07-15 11:43:56 来源:亿速云 阅读:216 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关C++中怎么实现对象的拷贝与赋值操作,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

拷贝构造函数,顾名思义,等于拷贝 + 构造。它肩负着创建新对象的任务,同时还要负责把另外一个对象拷贝过来。比如下面的情况就调用拷贝构造函数:

cstring str = strother;

赋值操作则只含有拷贝的意思,也就是说对象必须已经存在。比如下面的情况会调用赋值操作。

str = strother;

不过有的对象是隐式的,由编译器产生的代码创建,比如函数以传值的方式传递一个对象时。由于看不见相关代码,所以不太容易明白。不过我们稍微思考一下,就会想到,既然是根据一个存在的对象拷贝生成新的对象,自然是调用拷贝构造函数了。

两者实现时有什么差别呢?我想有人会说,没有差别。呵,如果没有差别,那么只要实现其中一个就行了,何必要两者都实现呢?不绕圈子了,它们的差别是:

拷贝构造函数对同一个对象来说只会调用一次,而且是在对象构造时调用。此时对象本身还没有构造,无需要去释放自己的一些资源。而赋值操作可能会调用多次,你在拷贝之前要释放自己的一些资源,否则会造成资源泄露。

明白了这些道理之后,我们不防写个测试程序来验证一下我们的想法:

#include <stdio.h>  #include <stdlib.h>  #include <string.h>  class cstring  {   public:  cstring();  cstring(const char* pszbuffer);  ~cstring();  cstring(const cstring& other);  const cstring& operator=(const cstring& other);  private:  char* m_pszbuffer;;  };   cstring::cstring()  {  printf("cstring::cstring\n");  m_pszbuffer = null;  return;   }   cstring::cstring(const char* pszbuffer)  {  printf("cstring::cstring(const char* pszbuffer)\n");  m_pszbuffer = pszbuffer != null ? strdup(pszbuffer) : null;  return;  }  cstring::~cstring()  {  printf("%s\n", __func__);  if(m_pszbuffer != null)  {  free(m_pszbuffer);  m_pszbuffer = null;  }  return;  }  cstring::cstring(const cstring& other)  {  if(this == &other)  {  return;  }  printf("cstring::cstring(const cstring& other)\n");  m_pszbuffer = other.m_pszbuffer != null ? strdup(other.m_pszbuffer) : null;  }  const cstring& cstring::operator=(const cstring& other)  {  printf("const cstring& cstring::operator=(const cstring& other)\n");  if(this == &other)  {  return *this;  }   if(m_pszbuffer != null)  {  free(m_pszbuffer);  m_pszbuffer = null;  }  m_pszbuffer = other.m_pszbuffer != null ? strdup(other.m_pszbuffer) : null;  return *this;  }   void test(cstring str)  {  cstring str1 = str;  return;  }   int main(int argc, char* argv[])  {  cstring str;  cstring str1 = "test";  cstring str2 = str1;  str1 = str;  cstring str3 = str3;  test(str);  return 0;  }

看完上述内容,你们对C++中怎么实现对象的拷贝与赋值操作有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI