为什么在这种情况下调用空构造函数
Why is the empty constructor called in this case?
我是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进行了销毁。
相关文章:
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 确保所有构造函数调用相同的函数 c++ 设计模式
- 减少复制构造函数调用
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 在 Google 测试中,我可以从构造函数调用 GetParam() 吗?
- C++ - 从另一个类构造函数调用类构造函数
- 在C++中初始化带有和不使用构造函数调用的对象有什么区别
- 是否可以从移动构造函数调用默认构造函数?
- 在模板生成器模式中分解重复的构造函数调用
- std::atexit 从全局对象的构造函数调用时的排序
- 对构造函数调用的约束
- 编译器错过了无效的构造函数调用,并调用不存在的(或私有的)默认构造函数
- 用构造函数调用填充向量
- 创建指针时是否没有构造函数调用
- 使用 emplace_back 避免移动构造函数调用的最佳方法?
- C++ 抽象类构造函数调用
- 为什么函数参数将带有参数的构造函数调用
- 为什么比“构造函数”调用更多的“解构器”调用
- 将对象传递给函数并不是导致构造函数调用