详解C++句柄类

2020-01-06 19:25:37王冬梅

上一篇文件介绍了关于C++代理类的使用场景和实现方法,但是代理类存在一定的缺陷,就是每个代理类会创建一个新的对象,无法避免一些不必要的内存拷贝,本篇文章引入句柄类,在保持代理类多态性的同时,还可以避免进行不不要的对象复制。

我们先来看一个简易的字符串封装类:MyString,为了方便查看代码,将函数的声明和实现放到了一起。


class MyString
{
public:
 // 默认构造函数
 MyString()
 {
  std::cout << "MyString()" << std::endl;

  buf_ = new char[1];
  buf_[0] = '';
  len_ = 0;
 }

 // const char*参数的构造函数
 MyString(const char* str)
 {
  std::cout << "MyString(const char* str)" << std::endl;

  if (str == nullptr)
  {
   len_ = 0;
   buf_ = new char[1];
   buf_[0] = '';
  }
  else
  {
   len_ = strlen(str);
   buf_ = new char[len_ + 1];
   strcpy_s(buf_, len_ + 1, str);
  }
 }

 // 拷贝构造函数
 MyString(const MyString& other)
 {
  std::cout << "MyString(const MyString& other)" << std::endl;

  len_ = strlen(other.buf_);
  buf_ = new char[len_ + 1];
  strcpy_s(buf_, len_ + 1, other.buf_);
 }

 // str1 = str2;
 const MyString& operator=(const MyString& other)
 {
  std::cout << "MyString::operator=(const MyString& other)" << std::endl;

  // 判断是否为自我赋值
  if (this != &other)
  {
   if (other.len_ > this->len_)
   {
    delete[]buf_;
    buf_ = new char[other.len_ + 1];
   }

   len_ = other.len_;
   strcpy_s(buf_, len_ + 1, other.buf_);
  }

  return *this;
 }

 // str = "hello!";
 const MyString& operator=(const char* str)
 {
  assert(str != nullptr);

  std::cout << "operator=(const char* str)" << std::endl;

  size_t strLen = strlen(str);
  if (strLen > len_)
  {
   delete[]buf_;
   buf_ = new char[strLen + 1];
  }

  len_ = strLen;
  strcpy_s(buf_, len_ + 1, str);
  
  return *this;
 }
 
 // str += "hello"
 void operator+=(const char* str)
 {
  assert(str != nullptr);

  std::cout << "operator+=(const char* str)" << std::endl;

  if (strlen(str) == 0)
  {
   return;
  }

  size_t newBufLen = strlen(str) + len_ + 1;
  char* newBuf = new char[newBufLen];
  strcpy_s(newBuf, newBufLen, buf_);
  strcat_s(newBuf, newBufLen, str);

  delete[]buf_;
  buf_ = newBuf;

  len_ = strlen(buf_);
 }

 // 重载 ostream的 <<操作符 ,支持 std::cout << MyString 的输出
 friend std::ostream& operator<<(std::ostream &out, MyString& obj)
 {
  out << obj.c_str();
  return out;
 }

 // 返回 C 风格字符串
 const char* c_str()
 {
  return buf_;
 }

 // 返回字符串长度
 size_t length()
 {
  return len_;
 }

 ~MyString()
 {
  delete[]buf_;
  buf_ = nullptr;
 }

private:
 char* buf_;
 size_t len_;
};