簡體   English   中英

使用類指針作為參數的復制構造函數VS構造函數

[英]copy constructor VS constructor with a class pointer as parameter

問題1: “自類類型的指針構造函數”是否具有適當的名稱/正式名稱?

Q2:為什么復制構造函數比“自類類型的指針構造函數”更出名?

還是在什么情況下必須使用復制構造函數而不是“自類類型的指針構造函數”?

class MyClass 
{
public:  
    int i;
    MyClass()
    {
        i = 20;
    }

    //Copy constructor
    MyClass(MyClass const & arg) 
    {
        i = arg.i;
    }

    //What kind of Constructor is this one? 
    MyClass(MyClass* pArg)
    {
        i = pArg->i;
    }
};

int main() {
    MyClass obj;
    MyClass* p = new MyClass();

    //call copy constructor
    MyClass newObj(obj);                //call copy constructor directly
    MyClass newObj2(*p);                //dereference pointer and then call copy constructor
    MyClass* pNew = new MyClass(*p);    //dereference pointer and then call copy constructor

    //Call THE constructor
    MyClass theObj(&obj);               //get the address, call THE constructor
    MyClass theObj2(p);                 //call pointer constructor directly
    MyClass* ptheNew = new MyClass(p);  //call pointer constructor directly
}

它沒有特殊名稱,因為它沒有特殊之處。

復制構造函數“比較有名”,因為它很特殊。 之所以特別是因為它是語言工作方式的基本組成部分。 如果你不聲明拷貝構造函數,在大多數類,一個將被隱為您定義。 它涉及許多基本操作,例如:

void foo(MyClass obj) // the copy ctor is (potentially) called to create this parameter
{
    ...
}

MyClass bar() // the copy ctor is (potentially) called when this function returns, and when it result is used
{
    ...
}

MyClass a;
MyClass b(a); // This calls the copy constructor
MyClass c = b; // So does this

請注意,在許多情況下,副本已被優化。 請參閱復制清除 同樣,在C ++ 11中,在許多曾經調用過復制構造函數的地方都調用了移動構造函數。 但是move構造函數也可以在可能發生復制省略的地方進行優化。

我想不出您使用它時使用“ THE構造函數”的許多原因。

另外,拷貝構造函數幾乎應該始終具有以下簽名:

MyClass(MyClass const &)

不是這個:

MyClass(MyClass &)

對於C ++中的對象,我們通常使用引用而不是指針。 我們可以使用引用來獲取對象的地址,然后可以使用“。”。 要訪問其方法或數據,它比'->'更簡單直接。 我認為沒有必要使用“ THE構造函數”。

暫無
暫無

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

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