首页 > 解决方案 > 为什么调用简单构造函数后调用复制构造函数?

问题描述

我试图理解复制构造函数,并阅读了这篇(https://www.tutorialspoint.com/cplusplus/cpp_copy_constructor.htm)教程点文章。但是,我无法理解何时在下面的代码中调用了复制构造函数。不只Line line(10)调用 Simple 构造函数,然后为 ptr 分配内存并将 ptr 的值设置为 10?

是因为我们将 line 作为参数传递给 display 吗?那么将对象作为参数传递是否总是调用复制构造函数?

#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!

标签: c++

解决方案


Line line(10) 不只调用 Simple 构造函数吗

是的。

是因为我们将 line 作为参数传递给 display 吗?

是的。

那么将对象作为参数传递是否总是调用复制构造函数?

不必要。例如,某些类型没有构造函数,因此复制它们不会调用构造函数。此外,如果您传递一个右值,则可能会调用移动构造函数。或者,如果实参的类型与形参的类型不同,则可以调用转换构造函数或转换运算符。

如果参数是引用(类型相同,因此不涉及转换),则不调用构造函数。


推荐阅读