欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C語言

當前位置:主頁 > 軟件編程 > C語言 >

詳解C++句柄類

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點擊: 次

上一篇文件介紹了關(guān)于C++代理類的使用場景和實現(xiàn)方法,但是代理類存在一定的缺陷,就是每個代理類會創(chuàng)建一個新的對象,無法避免一些不必要的內(nèi)存拷貝,本篇文章引入句柄類,在保持代理類多態(tài)性的同時,還可以避免進行不不要的對象復制。

我們先來看一個簡易的字符串封裝類:MyString,為了方便查看代碼,將函數(shù)的聲明和實現(xiàn)放到了一起。

class MyString
{
public:
 // 默認構(gòu)造函數(shù)
 MyString()
 {
  std::cout << "MyString()" << std::endl;

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

 // const char*參數(shù)的構(gòu)造函數(shù)
 MyString(const char* str)
 {
  std::cout << "MyString(const char* str)" << std::endl;

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

 // 拷貝構(gòu)造函數(shù)
 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_;
};

看一段測試程序

#include "MyString.h"

int _tmain(int argc, _TCHAR* argv[])
{
 MyString str1("hello~~");
 MyString str2 = str1;
 MyString str3 = str1;

 std::cout << "str1=" << str1 << ", str2=" << str2 << ", str3=" << str3;

 return 0;
}

輸出內(nèi)容如下:

可以看到,定義了三個MyString對象,str2和str3都是由str1拷貝構(gòu)造而來,而且在程序的運行過程中,str2和str3的內(nèi)容并未被修改,但是str1和str2已經(jīng)復制了str1緩沖區(qū)的內(nèi)容到自己的緩沖區(qū)中。其實這里可以做一個優(yōu)化,就是讓str1和str2在拷貝構(gòu)造的時候,直接指向str1的內(nèi)存,這樣就避免了重復的內(nèi)存拷貝。但是這樣又會引出一些新的問題:

1. 多個指針指向同一塊動態(tài)內(nèi)存,內(nèi)存改何時釋放?由誰釋放?

2. 如果某個對象需要修改字符串中的內(nèi)容,該如和處理?

解決這些問題,在C++中有兩個比較經(jīng)典的方案,那就是引用計數(shù)和Copy On Write。

在引用計數(shù)中,每一個對象負責維護對象所有引用的計數(shù)值。當一個新的引用指向?qū)ο髸r,引用計數(shù)器就遞增,當去掉一個引用時,引用計數(shù)就遞減。當引用計數(shù)到零時,該對象就將釋放占有的資源。

下面給出引用計數(shù)的一個封裝類:

class RefCount
{
public:

 RefCount() : count_(new int(1)){};

 RefCount(const RefCount& other) : count_(other.count_)
 {
  ++*count_;
 }

 ~RefCount()
 {
  if (--*count_ == 0)
  {
   delete count_;
   count_ = nullptr;
  }
 }

 bool Only()
 {
  return *count_ == 1;
 }

 void ReAttach(const RefCount& other)
 {
  // 更新原引用計數(shù)的信息
  if (Only())
  {
   delete count_;
  }
  else
  {
   --*count_;
  }

  // 更新新的引用計數(shù)的信息
  ++*other.count_;
  
  // 綁定到新的引用計數(shù)
  count_ = other.count_;
 }

 void MakeNewRef()
 {
  if (*count_ > 1)
  {
   --*count_;
   count_ = new int(1);
  }
 }

private:
 int* count_;
};

Copy On Write:就是寫時復制,通過拷貝構(gòu)造初始化對象時,并不直接將參數(shù)的資源往新的對象中復制一份,而是在需要修改這些資源時,將原有資源拷貝過來,再進行修改,就避免了不必要的內(nèi)存拷貝。

下面的代碼是完整的句柄類MyStringHandle。每一個句柄類,都包含一個引用計數(shù)的類,用來管理和記錄對MyString對象的引用次數(shù)。

class MyStringHandle
{
public:
 MyStringHandle() : pstr_(new MyString){}

 // 這兩種參數(shù)的構(gòu)造函數(shù)必須構(gòu)造一個新的MyString對象出來
 MyStringHandle(const char* str) : pstr_(new MyString(str)) {}
 MyStringHandle(const MyString& other) : pstr_(new MyString(other)) {}

 // 拷貝構(gòu)造函數(shù),將指針綁定到參數(shù)綁定的對象上,引用計數(shù)直接拷貝構(gòu)造,在拷貝構(gòu)造函數(shù)內(nèi)更新引用計數(shù)的相關(guān)信息
 MyStringHandle(const MyStringHandle& ohter) : ref_count_(ohter.ref_count_), pstr_(ohter.pstr_) {}

 ~MyStringHandle()
 {
  if (ref_count_.Only())
  {
   delete pstr_;
   pstr_ = nullptr;
  }
 }

 MyStringHandle& operator=(const MyStringHandle& other)
 {
  // 綁定在同一個對象上的句柄相互賦值,不作處理
  if (other.pstr_ == pstr_)
  {
   return *this;
  }

  // 若當前引用唯一,則銷毀當前引用的MyString
  if (ref_count_.Only())
  {
   delete pstr_;
  }

  // 分別將引用計數(shù)和對象指針重定向
  ref_count_.ReAttach(other.ref_count_);
  pstr_ = other.pstr_;

  return *this;
 }

 // str = "abc" 這里涉及到對字符串內(nèi)容的修改,
 MyStringHandle& operator=(const char* str)
 {
  if (ref_count_.Only())
  {
   // 如果當前句柄對MyString對象為唯一的引用,則直接操作改對象進行賦值操作
   *pstr_ = str;
  }
  else
  {
   // 如果不是唯一引用,則將原引用數(shù)量-1,創(chuàng)建一個新的引用,并且構(gòu)造一個新的MyString對象
   ref_count_.MakeNewRef();
   pstr_ = new MyString(str);
  }

  return *this;
 }

private:
 MyString* pstr_;
 RefCount ref_count_;
};

看一段測試程序:

int _tmain(int argc, _TCHAR* argv[])
{
 // 構(gòu)造MyString
 MyStringHandle str1("hello~~");

 // 不會構(gòu)造新的MyString
 MyStringHandle str2 = str1;
 MyStringHandle str3 = str1;
 MyStringHandle str4 = str1;

 // 構(gòu)造一個空的MyString
 MyStringHandle str5;

 // 將str1賦值到str5,不會有內(nèi)存拷貝
 str5 = str1;

 // 修改str5的值
 str5 = "123";
 str5 = "456";

 return 0;
}

總結(jié)

本篇文章介紹了C++句柄類的設(shè)計思想與簡單實現(xiàn),主要通過引用計數(shù)和Copy On Write實現(xiàn),這兩種思想還是很經(jīng)典的,垃圾回收、智能指針的實現(xiàn)都有借鑒這兩種思想。水平有限,可能會有一些錯誤或者描述不明確,歡迎大家拍磚~~

上一篇:opencv實現(xiàn)定時錄像功能

欄    目:C語言

下一篇:C語言實現(xiàn)兩個矩陣相乘

本文標題:詳解C++句柄類

本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/776.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有