为什么在这种情况下调用空构造函数

Why is the empty constructor called in this case?

本文关键字:构造函数 调用 这种情况下 为什么      更新时间:2024-09-23

我是C++的初学者,很难从练习本中理解这个程序,特别是为什么空构造函数总共调用了6次:

#include <iostream>
class Allo{
public:
Allo(int x_=0)
: x(x_)
{
std::cout << "A" << x << " ";
}
Allo(const Allo& autre)
: x(autre.x)
{
std::cout << "B" << x << " ";
}
~Allo() {
std::cout << "C" << x << " ";
}
int x;
};

void f1(Allo a1, Allo* a2, Allo* a3){
a1.x++;
a2->x -= 1;
a3+=1;
(a3->x)+=2000;
}
int main(){
Allo tab[3];
Allo a(20);
Allo* b = new Allo(5);
Allo* c = tab + 1;
f1(a, b, c);
std::cout << std::endl << "-------" << std::endl;
Allo* t = new Allo[4];
t[2] = Allo(9);
std::cout << std::endl;
return 0;
}

输出为:

A0 A0 A0 A20 A5 B20 C21 
-------
A0 A0 A0 A0 A9 C9 
C20 C2000 C0 C0

显示空构造函数在末尾被调用了4次。为什么?t[2] = Allo(9);不应该是调用构造函数的最后一行吗?

前言:A是常规构造函数,B是复制构造函数,C是析构函数(不是构造函数(。

让我分解每一行:

Allo tab[3];

3个用构造函数A构造的对象,用x=0初始化。这些是堆栈分配的。

Allo a(20);

1个用A构造的对象,x=20。这是堆栈分配的。

Allo* b = new Allo(5);

1个用A构造的对象,x=5。这是堆分配的。

Allo* c = tab + 1;

0个对象,这与Allo* c = &tab[1]相同。

f1(a, b, c);

1个用B构造的对象副本,x=20(因为第一个参数是按值传递的(。当x=21时,该对象在f1结束时被销毁(使用C(。

std::cout << std::endl << "-------" << std::endl;
Allo* t = new Allo[4];

4个用A构造的对象,x=0。这些是堆分配的。

t[2] = Allo(9);
std::cout << std::endl;
return 0;
}

1个用A构造的对象,x=9。这是堆栈分配的。

5个对象(此函数中所有堆栈分配的对象(以与末尾构造相反的顺序用C进行了销毁。