复制构造函数的理解

Copy constructor understanding

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

我正经历这一切,再次学习复制构造函数。

代码:

#include <iostream>
using namespace std;
class Line
{
   public:
      int getLength( void );
      Line( int len );             // simple constructor
      Line( const Line &obj);  // copy constructor
      ~Line();                     // destructor
   private:
      int *ptr;
};
// Member functions definitions including constructor
Line::Line(int len)
{
    cout << "Normal constructor allocating ptr" << endl;
    // allocate memory for the pointer;
    ptr = new int;
    *ptr = len;
}
Line::Line(const Line &obj)
{
    cout << "Copy constructor allocating ptr." << endl;
    ptr = new int;
   *ptr = *obj.ptr; // copy the value
}
Line::~Line(void)
{
    cout << "Freeing memory!" << endl;
    delete ptr;
}
int Line::getLength( void )
{
    return *ptr;
}
void display(Line obj)
{
   cout << "Length of line : " << obj.getLength() <<endl;
}
// Main function for the program
int main( )
{
   Line line(10);
   display(line);
   return 0;
}

输出:

Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!

我想知道它为什么在Line line(10)中调用Copy构造函数。我认为它应该只调用普通构造函数。我不会在这里克隆任何对象。请有人给我解释一下。

由于函数参数是按值传递的,因此调用了复制构造函数。此处
void display(Line obj)

该函数被定义为按值取CCD_ 2参数。这将导致生成一个论点的副本。如果您通过引用传递,复制构造函数将不会被称为

我想知道它为什么在Line line(10)中调用Copy构造函数

不,没有
它只是调用Line类构造函数的构造函数,该构造函数以int为参数。


void display(Line obj)    

通过值传递Line对象,因此会调用复制构造函数来创建传递给函数的副本。

在C++中,函数参数默认按值传递。这些对象的副本是通过调用该类的副本构造函数来创建的。