最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解C++句柄類

 更新時間:2018年06月12日 08:24:55   作者:lzm_cn  
本篇文章給大家詳細分析了C++句柄類的相關(guān)知識點,對此有需要的朋友跟著學(xué)習(xí)參考下吧。

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

我們先來看一個簡易的字符串封裝類: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 風(fēng)格字符串
 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)復(fù)制了str1緩沖區(qū)的內(nèi)容到自己的緩沖區(qū)中。其實這里可以做一個優(yōu)化,就是讓str1和str2在拷貝構(gòu)造的時候,直接指向str1的內(nèi)存,這樣就避免了重復(fù)的內(nèi)存拷貝。但是這樣又會引出一些新的問題:

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

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

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

在引用計數(shù)中,每一個對象負責(zé)維護對象所有引用的計數(shù)值。當(dāng)一個新的引用指向?qū)ο髸r,引用計數(shù)器就遞增,當(dāng)去掉一個引用時,引用計數(shù)就遞減。當(dāng)引用計數(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:就是寫時復(fù)制,通過拷貝構(gòu)造初始化對象時,并不直接將參數(shù)的資源往新的對象中復(fù)制一份,而是在需要修改這些資源時,將原有資源拷貝過來,再進行修改,就避免了不必要的內(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;
  }

  // 若當(dāng)前引用唯一,則銷毀當(dāng)前引用的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())
  {
   // 如果當(dāng)前句柄對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)都有借鑒這兩種思想。水平有限,可能會有一些錯誤或者描述不明確,歡迎大家拍磚~~

相關(guān)文章

  • 淺談VC中預(yù)編譯的頭文件放那里的問題分析

    淺談VC中預(yù)編譯的頭文件放那里的問題分析

    本篇文章是對VC中預(yù)編譯的頭文件放那里的問題進行了詳細的分析介紹,需要的朋友參考下
    2013-05-05
  • C++實踐排序函數(shù)模板項目的參考方法

    C++實踐排序函數(shù)模板項目的參考方法

    今天小編就為大家分享一篇關(guān)于C++實踐排序函數(shù)模板項目的參考方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-02-02
  • C++如何實現(xiàn)簡易掃雷游戲

    C++如何實現(xiàn)簡易掃雷游戲

    這篇文章主要為大家詳細介紹了C++如何實現(xiàn)簡易掃雷游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-03-03
  • 全排列算法的原理和實現(xiàn)代碼

    全排列算法的原理和實現(xiàn)代碼

    這篇文章主要介紹了全排列算法的原理和實現(xiàn)代碼,全排列是將一組數(shù)按一定順序進行排列,如果這組數(shù)有n個,那么全排列數(shù)為n!個,需要的朋友可以參考下
    2014-08-08
  • C++ Clock類模擬實現(xiàn)鬧鐘運行

    C++ Clock類模擬實現(xiàn)鬧鐘運行

    這篇文章主要為大家詳細介紹了C++ Clock類模擬實現(xiàn)鬧鐘運行,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • C++中的關(guān)鍵字volatile詳解

    C++中的關(guān)鍵字volatile詳解

    這篇文章主要介紹了C++中的關(guān)鍵字volatile使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-03-03
  • 一文詳細講解C++精妙的哈希算法

    一文詳細講解C++精妙的哈希算法

    這篇文章主要介紹了C++精妙的哈希算法的相關(guān)資料,哈希結(jié)構(gòu)通過哈希函數(shù)將關(guān)鍵碼映射到表中的特定位置,以提高搜索效率,理想的哈希函數(shù)應(yīng)保證一致性、哈希值均勻分布、高計算效率與最小化沖突,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-10-10
  • 詳解C語言結(jié)構(gòu)體的定義和使用

    詳解C語言結(jié)構(gòu)體的定義和使用

    這篇文章主要為大家介紹了C語言結(jié)構(gòu)體的定義和使用,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-12-12
  • 一文讓你徹底明白C++中的const

    一文讓你徹底明白C++中的const

    這篇文章主要給大家介紹了關(guān)于C++中const的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • C語言頭文件<string.h>函數(shù)詳解

    C語言頭文件<string.h>函數(shù)詳解

    本文主要介紹了C語言頭文件<string.h>函數(shù)詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07

最新評論

淮阳县| 伊吾县| 巴彦县| 凯里市| 依安县| 呼图壁县| 德安县| 海丰县| 观塘区| 桐庐县| 社旗县| 蕉岭县| 威远县| 同德县| SHOW| 东港市| 逊克县| 海盐县| 兰西县| 彝良县| 洱源县| 麻江县| 盐山县| 临漳县| 嵩明县| 雅安市| 兴国县| 富裕县| 海南省| 舒城县| 黔西| 宝鸡市| 清新县| 凤台县| 沙田区| 罗源县| 襄城县| 辽中县| 班戈县| 宜君县| 平安县|