c 寫時拷貝

2021-08-04 14:31:14 字數 1634 閱讀 2730

在c++中乙個類有六個預設成員函式,其中拷貝建構函式分為淺拷貝和深拷貝;

淺拷貝是一種值拷貝,深拷貝不僅是值拷貝,還要做其他處理;

深淺拷貝的區別:

由上圖可知當乙個拷貝構造乙個需動態開闢空間的物件時,用淺拷貝時會出現同一塊空間被釋放兩次,這樣顯然有問題,用深拷貝的話可以解決此問題,但當拷貝構造出來的物件,不需要修改時,使用深拷貝就有些浪費空間了,採用引用計數的寫時拷貝能更好的解決問題。

寫時拷貝,按其意思來說就是在「寫」(修改)的時候進行拷貝,它要實現的是既不浪費空間,又不使同一空塊空間析構多次;因此它才用引用計數的方法來實現寫時拷貝;(以string類為例)

具體**如下:

#define _crt_secure_no_warnings 1

#include

using namespace std;

class string

string(const string& s)

:_str(s._str)

,_refcount(null)

string& operator=(const string& s)

return *this;

} ~string()

public:

void copyonwrite() }

void release() }

private:

char *_str;

int *_refcount;

};int main()

以上這種方法,建立物件時需要都需給_refcount建立新的空間,釋放的時候也需釋放兩次,效率比較低,那能不能進行改進呢?

原理圖:

具體**:

#define _crt_secure_no_warnings 1

//引用計數的寫時拷貝(淺拷貝)

#include

using namespace std;

class string

string(const string& s)

:_str(s._str)

~string()

string& operator=(const string& s)

_str=s._str ;

getrefcount()++;

} }void release()

}public :

int& getrefcount()

char* getstr()

char& operator(size_t pos)

private:

char *_str;

};int main()

{ string s1("hello");

string s2(s1);

string s3=s2;

s3[1]='m';

cout<

<

c 寫時拷貝1

class string string const string s ptr new char strlen s.ptr 1 另外開闢空間 string private char ptr void test int end gettickcount 記錄此時毫秒數 string const stri...

C 寫時拷貝技術

寫時拷貝 就是在寫的時候 修改字串的時 才會進行真正的空間分配,在唯讀的情況下,資料進行淺拷貝。寫時拷貝技術就是引用計數器的淺拷貝,是通過 引用計數 實現的,在分配空間的時候多分配4個位元組,用來記錄有多少個指標指向這塊空間。當有新的指標指向這塊空間時,引用計數加1 當要釋放這塊空間時,僅引用計數減...

C 淺拷貝 深拷貝 寫時拷貝

淺拷貝 編譯器只是直接將指標的值拷貝過來,結果多個物件共用了一塊記憶體,當乙個物件呼叫了析構函式將這塊記憶體釋放掉之後,另一些物件不知道這塊空間已經還給了系統,再次呼叫析構函式進行釋放時發現已經釋放了,就會造成程式崩潰。在類的成員中有指標型別的成員變數的時候,必須對其寫出顯式的拷貝建構函式和賦值運算...