簡體   English   中英

具有復制構造函數的C ++不能正常工作

[英]C++ with copy constructor doesn't work good

我建立了一個名為Attribute的對象,該對象具有完整副本和空構造函數。 然后,我建立了另一個名為Human的對象,其中包含Attribute對象。 當我嘗試以某種方式構建人類類(具有完整的構造函數)時,它會自動調用Attribute copy構造函數,我不知道為什么。

這是代碼:

char** d = new char*[3];    
    d[0] = new char[10];
    d[0] = "aa";
    d[1] = new char[10];
    d[1] = "bb";
    d[2] = new char[10];
    d[2] = "cc";

    Attribute *a = new Attribute(1.7, "blue", "white", "black", d, 3);
    Human *h = new Human("Name", *a);

當我使用調試器並轉到此行時:new Human(“ Name”,* a); 它會自動進入此功能:

Attribute::Attribute(Attribute& copy)       
{
    Attribute(copy.height, copy.eyeColor, copy.skinColor, copy.hairColor, copy.diseases, copy.numOfDiseases);
}

並且只有在此函數結束后,它才會啟動Human完整構造函數...

Human *h = new Human("Name", *a);
                              ^----- Here it's passing in an Attribute by value

因此調用了屬性副本構造函數。

復制構造函數沒有初始化任何東西。 它只是創建並銷毀本地臨時對象。

在C ++ 11中,您可以將工作委托給另一個構造函數,就像您正在嘗試做的那樣:

Attribute::Attribute(Attribute const & copy) :
    Attribute(copy.height, copy.eyeColor, copy.skinColor, copy.hairColor, copy.diseases, copy.numOfDiseases)
{}

從歷史上看,您必須復制另一個構造函數的代碼,或將其移至兩個構造函數都調用的函數中。

您可能還希望通過引用獲取構造函數參數,以便不需要復制它們:

Human(std::string const & name, Attribute const & attribute);

除非確實需要,否則還應避免使用new 您可能想要更多類似的東西

Attribute a(1.7, "blue", "white", "black", d, 3);
Human h("Name", a);

當您確實確實需要new的對象時(通常是因為您希望對象超出當前范圍,或者有時是出於多態性),請使用RAII管理類型(如智能指針和容器)而不是原始指針,以確保對象一旦被正確刪除即可完成他們。 處理原始指針是內存泄漏和其他災難的良方。

a-是指針* a-是值

因此,如果您的Human構造函數按值接受seconds參數

Human::Human(char* s, Attribute a)

它將復制屬性並為其使用復制構造函數。 如果您不希望出現這種情況,則可以通過指針傳遞參數。

Human::Human(char* s, Attribute *a)

並這樣稱呼它:

Attribute *a = new Attribute(1.7, "blue", "white", "black", d, 3);
Human *h = new Human("Name", a); // this works with pointer now. Pointer will be copied, but the class will remain in the same memory and wouldn't be copied anywhere.

如果考慮到這一點,其行為類似於正常值和函數:

void f1(int a){ a++; cout << a; }
void f2(int *a){ *a++; cout << *a; }

int b = 4;
f1(b); // It copies the value of local b to parameter a, increments local parameter a of f1 and prints it; It will print 5
cout << b; // b will remain the same. It will print 4
f2(&b); // It copies pointer, but both pointers &b and a point to the same variable b from this scope, and it's value is not copied 
cout << b; // As we've worked with pointers, it was incremented in f2. It will print 5

請注意,您必須處理所有指針的責任。 如果您手動創建了某些內容,請不要忘記將其刪除,在某些情況下可能會泄漏。 使用smart_pointers可以輕松得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM