解释此 c++ 代码

Explain this c++ code

本文关键字:代码 c++ 解释      更新时间:2023-10-16
#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
构造函数被

调用一次,析构函数被调用两次这里有什么好开心的?这是未定义的行为吗?

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

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

A b(a)
A b = a

这两个都调用它。

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

添加此代码以查看它。维基百科有更多信息。

在代码段中

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;
    }
};

默认复制构造函数用于创建第二个实例。当您离开范围时,将调用两个对象的干扰符

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

应用退出后,由于有两个对象,因此将调用析构函数方法两次。

A

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