【问题标题】:Explain this c++ code解释这段 C++ 代码
【发布时间】:2013-08-24 22:19:53
【问题描述】:
#include <iostream>
using namespace std;

class A
{
    int n;
public:
    A()
    {
        cout << "Constructor called" << endl;
    }
    ~A()
    {
        cout << "Destructor called" << endl;
    }
};

int main()
{
    A a;           //Constructor called
    A b = a;       //Constructor not called
    return 0;
}

输出:

Constructor called
Destructor called
Destructor called

构造函数被调用一次,而析构函数被调用两次 这里发生了什么?这是未定义的行为吗?

【问题讨论】:

    标签: c++ object constructor destructor


    【解决方案1】:

    第二行调用所谓的复制构造函数。就像律师一样,如果你没有,编译器会为你提供一个。

    它是一种特殊类型的转换器,当你用另一个相同类型的变量初始化一个变量时会调用它。

    A b(a)
    A b = a
    

    这两个都调用它。

    A(const A& a)
    {
        cout << "Copy Constructor called" << endl;
        //manually copy one object to another
    }
    

    添加此代码以查看它。 Wikipedia 有更多信息。

    【讨论】:

      【解决方案2】:

      在sn-p中

      A b = a

      你调用的不是你的构造函数,而是生成的拷贝构造函数:

      class A
      {
          int n;
      public:
          A()
          {
              cout << "Constructor called" << endl;
          }
          A(const A& rv)
          {
              cout << "Copy constructor called" << endl;
              // If you are not using default copy constructor, you need
              // to copy fields by yourself.
              this->n = rv.n;
          }
          ~A()
          {
              cout << "Destructor called" << endl;
          }
      };
      

      【讨论】:

        【解决方案3】:

        Default Copy Constructor 用于创建第二个实例。 当您离开作用域时,两个对象的析构函数都会被调用

        【讨论】:

          【解决方案4】:

          创建了对象 A 的两个实例。一个由构造函数创建,另一个由复制构造函数创建。由于您没有明确定义一个,因此编译器为您完成了这项工作。

          一旦应用退出,由于有两个对象,析构方法被调用了两次。

          【讨论】:

          • 不是operator=
          • 不是赋值运算符,和operator=一样
          【解决方案5】:

          A b=a => A b(a) => 这会调用类的默认复制构造函数。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-07-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-11-14
            • 1970-01-01
            相关资源
            最近更新 更多