析构函数调用的构造函数调用数量过多
Destructor calls out-numbering constructor calls
我试图了解构造函数和析构函数的确切工作原理,但有点偶然发现了这段代码,并且发现很难理解为什么析构函数被调用了 4 次而不是构造函数。请帮助我了解此 pgm 的流程。
#include<iostream>
using namespace std;
#define PRINT(N) cout << #N <<endl;
class Player
{
private:
int Health;
int Wealth;
public:
Player(int x = 0, int y = 0): Health(x), Wealth(y) //initializing with constructor
{
cout << " Constructor is called " << endl;
}
void sethealth(int num)
{
Health = num;
}
void setwealth(int num)
{
Wealth = num;
}
int gethealth()
{
return Health;
}
int getwealth()
{
return Wealth;
}
~Player() // Destructor being called
{
cout << " Destructor is called " << endl;
}
};
void _display(Player _obj)
{
cout << "Players health is " << _obj.gethealth() << endl;
cout << "Player's wealth is " << _obj.getwealth() << endl;
}
int main()
{
Player player1, player2;
int num1 = 100, num2 = 150, num3 = 10, num4 = 20;
player1.sethealth(num1);
player2.sethealth(num2);
player1.setwealth(num3);
player2.setwealth(num4);
PRINT(player1);
_display(player1);
PRINT(player2);
_display(player2);
return 0;
}
输出如下所示:如您所见,构造函数的调用是预期的两倍,但是为什么在 main() 退出后会在两者之间和再次调用析构函数
Constructor is called
Constructor is called
player1
Players health is 100
Player's wealth is 10
Destructor is called
player2
Players health is 150
Player's wealth is 20
Destructor is called
Destructor is called
Destructor is called
Press any key to continue . . .
当您调用以下函数时,它会调用复制构造函数:
void _display(Player _obj){
cout << "Players health is " <<_obj.gethealth() <<endl;
cout <<"Player's wealth is "<< _obj.getwealth() <<endl;
}
您可以定义自己的复制构造函数以查看效果。
Player(const Player& temp):Health(temp.Health), Wealth(temp.Wealth) {
std::cout << "Copy constructor was called." << std::endl;
}
仅供建议:如果您想避免额外的副本并且您的唯一目的是从对象中读取数据,则应通过引用传递它:
void _display(const Player &_obj){
cout << "Players health is " <<_obj.gethealth() <<endl;
cout <<"Player's wealth is "<< _obj.getwealth() <<endl;
}
您的 display
函数按值获取参数,这意味着创建了一个副本 - 并且该副本也需要被销毁。
您缺少复制构造函数:
class Player{
// ...
public:
Player(const Player& other):Health(other.Health), Wealth(other.Wealth) {
cout << "copy ctor" << endl;
}
// ...
};
相关文章:
- 什么时候调用析构函数
- C++-明确何时以及如何调用析构函数
- 在c++中使用向量时,如何调用构造函数和析构函数
- C++ 防止在映射中放置()时调用析构函数
- 调用析构函数以释放动态分配的内存
- C++:使用方法调用析构函数的顺序是什么?
- 向量推回调用析构函数时调用析构函数
- 如何在调用析构函数时优雅地停止/销毁带有阻塞调用C++线程?
- C++,我应该调用析构函数吗?
- 如何获取有关在 Clang LibTooling 中调用析构函数的信息?
- 当我从 std::vector 中的新放置调用析构函数时会发生什么?
- 未调用的初始化静态thread_local结构的构造函数和析构函数
- 为什么这里不调用析构函数
- 在调用 std::bind 的产品后意外调用析构函数
- 为什么在传递给函数而不是构造函数时调用析构函数?
- 如何在C++中调用析构函数
- 为什么为未删除的对象调用析构函数?
- 调用析构函数时出错
- C++ 在不释放内存的情况下调用析构函数
- 从函数调用析构函数返回的对象