C++的拷贝构造,拷贝复制和析构

  • String class

#ifndef __MYSTRING__
#define __MYSTRING__

class String
{
  ... ...
};

String::function(...)...
Global-function

#endif
{
  //构造函数
  String s1();
  String s2("hello");

  String s3(s1);//构造一个String类型的变量,以s1为初值-->拷贝构造
  cout << s3 << endl;
  s3 = s2;//将s2赋值给s3,拷贝赋值

  cout << s3 <<endl;
}

之前的Complex类没有写拷贝构造和拷贝赋值函数,编译器会加上默认的。
要不要重写拷贝构造和拷贝赋值函数,就要看默认的那一套够不够用。
如果是带有指针的类,用默认的那一套,会有很大的问题。

  • Big Three,三个特殊的函数

class String
{
public:
  String(const char* cstr = 0);
  String(const String& str);//拷贝构造函数
  String& operator=(const String& str);//拷贝赋值函数(操作符重载)
  ~String();//析构函数
  char* get_c_str() const {return m_data;};
private:
  char* m_data;
};
  • ctor和dtor(构造函数和析构函数)

inline
String::String(const char* cstr = 0)
{
  if (cstr) {
    m_data = new char[strlen(cstr) + 1];
    strcpy(m_data, cstr);
  } else {
    m_data = new char[1];
    *m_data = '\0';
  }
}
inline
String::~String()
{
  delete[] m_data;
}
{
  String s1();
  String s2("hello");

  String* p = new String("hello");
  delete p;
}
  • class with pointer members必须有copy ctor和copy op=

使用默认的拷贝构造(default copy ctor)或拷贝赋值(default op=)就会造成内存泄漏。

  • copy ctor(拷贝构造函数)

深拷贝

inline
String::String(const String& str)
{
  m_data = new char[strlen(str.m_data) + 1];//直接取另一个object的private data
  //兄弟之间互为friend-->相同class的各个objects互为friends(友元)
  strcpy(m_data, str.m_data);
}
{
  String s1("hello");
  String s2(s1);
//String s2 = s1;
}
  • copy assignment operator(拷贝赋值函数)

inline String&
String::operator=(const String& str)
{
  if(this == &str)//检测自我赋值(self assignment)
    return *this;

  delete [] m_data;
  m_data = new char[strlen(str.m_data) + 1];
  strcpy(m_data, str.m_data);
  return *this;
}
{
  String s1("hello");
  String s2(s1);
  s2 = s1;
}
  • 13
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值