即使没有任何要复制的对象,是否会自动调用复制构造函数?

is copy constructor called automatically even when there isn't any object to be copied?

本文关键字:复制 是否 构造函数 调用 对象 任何      更新时间: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!

我不明白为什么没有作为复制构造函数的参数传递的对象,为什么要调用复制构造函数?另外,在调试时,我了解函数主完成功能后被调用。为什么称呼它,以及为什么在函数主终止后被调用?谢谢,

void display(Line obj) {

此功能按值采用其参数。这意味着将此参数传递给此功能将复制它。当main()调用display()

时,这是调用复制构造函数

如果您更改此功能,以便通过参考来采用其参数:

void display(Line &obj) {

您会发现复制构造函数不再从您的示例程序中调用。

您将在C 书中找到有关按值与参考的传递参数的更多信息。

函数显示按值将其参数取值,因此调用复制构造函数。如果不想要,请通过参考 - 线&amp;OBJ。更好的是,按照const参考 - const行&amp;OBJ。但是在后一种情况下,您在显示内部的成员函数也必须是const。

display()中的参数:

void display(Line obj)

调用复制构造函数,因为在函数的参数中正在制作一个新对象。因此,将您传递给此功能的类Line的任何对象都将被复制并用作功能主体的过度。

您在以下行中调用此功能:

display(line);

因此,line的副本是在display()中制作的。为避免这种情况,请参考Line类的对象。将参数在函数标题中传递的方式更改为:

void display(Line &obj)

以这种方式,您仅引用对象,因此,不做副本。因此,复制构造函数不会在此处调用。

相关文章: