【问题标题】:How does the copy constructor work in this code?复制构造函数在这段代码中是如何工作的?
【发布时间】:2020-11-12 17:11:48
【问题描述】:

我一直在阅读 Bruce Eckel 的“Thinking in C++”,并且遇到了复制构造函数。虽然我主要了解对复制构造函数的需求,但我对以下代码有点困惑:

#include <iostream>
using namespace std;

class foo  
{
    static int objCount;
public:
    foo()
    {
        objCount++;
        cout<<"constructor :"<<foo::objCount<<endl;
    }
    ~foo()
    {
        objCount--;
        cout<<"destructor :"<<foo::objCount<<endl;
    }

};

int foo::objCount=0;
int main()
{
    foo x;
    foo y = x;
    return 0;
}

在上面的代码中,构造函数被调用一次,析构函数被调用两次。 以下是我不明白的:

  1. yclass foo的对象,那为什么编译器不调用构造函数,然后将x的内容复制到y中呢?

  2. 编译器提供的默认复制构造函数在这张图中的位置在哪里?

【问题讨论】:

    标签: c++ copy-constructor


    【解决方案1】:

    y是foo类的对象,为什么编译器不调用构造函数,然后将x的内容复制到y中呢?

    确实如此。

    它调用 copy 构造函数来做这件事。

    编译器提供的默认复制构造函数在这张图中的位置在哪里?

    您没有提供自己的复制构造函数来产生任何输出,因此会调用自动生成的构造函数(它不会)。

    默认构造函数(看起来像foo())在复制期间根本不会被调用。只有复制构造函数(看起来像 foo(const foo&amp;) 的那个)。

    每个构造只发生 一个 构造函数。好吧,除非你使用委托构造函数,但我们改天再讨论。 ?


    #include <iostream>
    using namespace std;
    
    class foo  
    {
        static int objCount;
    public:
        foo()
        {
            objCount++;
            cout<<"constructor :"<<foo::objCount<<endl;
        }
        foo(const foo&)
        {
            objCount++;
            cout<<"copy constructor :"<<foo::objCount<<endl;
        }
        ~foo()
        {
            objCount--;
            cout<<"destructor :"<<foo::objCount<<endl;
        }
    
    };
    
    int foo::objCount=0;
    
    int main()
    {
        foo x;
        foo y = x;
        return 0;
    }
    
    // constructor :1
    // copy constructor :2
    // destructor :1
    // destructor :0
    

    【讨论】:

      【解决方案2】:
      1. y 是类 foo 的对象,为什么编译器不调用 构造函数,然后将 x 的内容复制到 y 中?

      在这种情况下,它调用的不是构造函数,而是复制构造函数(您没有指定,但编译器创建了它)。这里新建了一个对象y,所以需要构造(复制构造,因为你使用了其他对象x)。

      foo y = x;
      
      1. 编译器提供的默认复制构造函数在哪里适合 在这张照片中?

      您也可以查看this问题。有编译器隐式创建的其他函数的解释。有时可能会令人沮丧(尤其是当您使用原始指针时),因此您应该了解这些功能。

      【讨论】:

      • 你分享的关于编译器创建的隐式函数的资源真的很有帮助。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多