析构函数调用的构造函数调用数量过多

Destructor calls out-numbering constructor calls

本文关键字:函数调用 析构      更新时间:2023-10-16

我试图了解构造函数和析构函数的确切工作原理,但有点偶然发现了这段代码,并且发现很难理解为什么析构函数被调用了 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;
  }
// ...
};