c++ - 即使没有要复制的对象,复制构造函数也会自动调用吗?

标签 c++ constructor copy-constructor

我在网上找到了这段代码:

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

我不明白为什么在没有对象作为参数传递给复制构造函数时调用复制构造函数? 另外,在调试时,我了解到在函数 main 完成后调用了析构函数。为什么调用它以及为什么在函数 main 终止后调用它? 谢谢,

最佳答案

void display(Line obj) {

此函数按值获取其参数。这意味着将此参数传递给此函数将复制它。当 main() 调用 display() 时,这是调用复制构造函数的地方。

如果您更改此函数,使其通过引用获取其参数:

void display(Line &obj) {

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

您会在 C++ 书籍中找到有关按值传递参数与按引用传递参数的更多信息。

关于c++ - 即使没有要复制的对象,复制构造函数也会自动调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42789311/

相关文章:

c++ - 我如何构建默认使用我自己构建的 libc++ 的 clang?

c++ - 我可以在函数调用之间维护 C++ DLL 中的内存吗?

c++ - 如果模板构造函数参数是从非模板基类(Armadillo)派生的,它们似乎并不关心它们的类型。

c++ - 从重载 + 运算符返回到重载 = 运算符时不调用复制构造函数

c++ - 通过引用隐式调用不兼容参数的复制构造函数?

c++ - 关于包含不可复制成员引用的类的复制构造函数的建议

c++ - C++中的 namespace 搜索

c++ - boost::interprocess vector 崩溃

c++ - 为什么 g++ 似乎混淆了数据类型?

c++ - SFINAE 和 noexcept 说明符