詳解C++句柄類
上一篇文件介紹了關(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)文章
簡單介紹C語言中的umask()函數(shù)和truncate()函數(shù)
這篇文章主要介紹了簡單介紹C語言中的umask()函數(shù)和truncate()函數(shù),是C語言入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-09-09
QML中動態(tài)與靜態(tài)模型應(yīng)用詳解
QML是一種描述性的腳本語言,文件格式以.qml結(jié)尾。語法格式非常像CSS(參考后文具體例子),但又支持javascript形式的編程控制。QtDesigner可以設(shè)計出·ui界面文件,但是不支持和Qt原生C++代碼的交互2022-08-08
基于Windows API實現(xiàn)遍歷所有文件并刪除的方法
這篇文章主要介紹了基于Windows API實現(xiàn)遍歷所有文件并刪除的方法,是win32應(yīng)用程序的一個比較典型的文件操作應(yīng)用技巧,需要的朋友可以參考下2015-04-04
VSCode配置C/C++并添加非工作區(qū)頭文件的方法
這篇文章主要介紹了VSCode配置C/C++并添加非工作區(qū)頭文件的方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03
C++實現(xiàn)LeetCode(88.混合插入有序數(shù)組)
這篇文章主要介紹了C++實現(xiàn)LeetCode(88.混合插入有序數(shù)組),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07
C語言數(shù)據(jù)結(jié)構(gòu)深入探索順序表
順序表,全名順序存儲結(jié)構(gòu),是線性表的一種,線性表用于存儲邏輯關(guān)系為“一對一”的數(shù)據(jù),順序表自然也不例外,不僅如此,順序表對數(shù)據(jù)的物理存儲結(jié)構(gòu)也有要求,跟隨下文來具體了解吧2022-03-03

