
什麼時候需要使用者定義的複製建構子?
C 編譯器會自動為類別產生一個複製建構函數,該構造函數以成員方式執行預設複製。然而,在某些情況下,我們可能需要定義自己的使用者定義的複製建構函式。
定義使用者定義的複製建構子的原因:
- 深度複製:當類別的成員變數分配需要單獨複製的動態記憶體時,逐成員複製是不夠的。在這種情況下,需要使用者定義的複製建構函式來執行深度複製,這會為物件的成員變數建立動態記憶體的新副本。
範例:
考慮以下儲存字串的類別:
1 2 3 4 5 6 7 | <code class = "cpp" > class Class {
public :
Class( const char* str);
~Class();
private :
char* stored;
};</code>
|
登入後複製
使用預設的複製建構函數,儲存的成員只能透過引用複製,當其中一個副本被複製時,會導致未定義的行為被毀了。為了防止這種情況,我們定義了一個執行深度複製的使用者定義的複製建構子:
1 2 3 4 | <code class = "cpp" >Class::Class( const Class& another) {
stored = new char[ strlen (another.stored) + 1];
strcpy(stored, another.stored);
}</code>
|
登入後複製
此外,賦值運算子也需要使用者定義的複製建構函式才能正確執行深度複製:
1 2 3 4 5 6 | <code class = "cpp" >void Class::operator = ( const Class& another) {
char* temp = new char[ strlen (another.stored) + 1];
strcpy(temp, another.stored);
delete [] stored;
stored = temp;
}</code>
|
登入後複製
以上是什麼時候應該在 C 中實作使用者定義的複製建構函式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!