复制构造函数 VS 构造函数,并将类指针作为参数

copy constructor VS constructor with a class pointer as parameter

本文关键字:构造函数 指针 参数 VS 复制      更新时间:2023-10-16

Q1:"self class typed pointer constructor"是否有一个体面/正式的名称?

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

请注意,在许多情况下,副本被优化掉了。请参阅复制 Elision。 此外,在 C++11 中,移动构造函数在以前调用复制构造函数的许多地方被调用。 但是移动构造函数也可以在可能发生复制省略的相同位置进行优化。

我想不出你使用"THE constructor"的很多原因,正如你所说的那样。

附带说明一下,复制构造函数几乎总是应该具有以下签名:

MyClass(MyClass const &)

不是这个:

MyClass(MyClass &)

对于C++中的对象,我们通常使用引用而不是指针。我们可以使用引用来获取对象的地址,并且比您可以使用 '." 来访问它的方法或数据,它比 '->' 更简单、更直接。我认为没有必要使用"THE 构造函数"。