析构函数调用out-numbering构造函数调用

时间:2014-12-01 08:56:05

标签: c++

我试图理解构造函数和析构函数是如何工作的,但有点绊倒了这段代码并且发现很难理解为什么析构函数被调用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 . . .

3 个答案:

答案 0 :(得分:2)

调用以下函数时调用复制构造函数:

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

答案 1 :(得分:1)

你的display函数按值获取参数,这意味着创建了一个副本 - 并且该副本也需要被破坏。

答案 2 :(得分:1)

您缺少复制构造函数:

class Player{
// ...
public:
  Player(const Player& other):Health(other.Health), Wealth(other.Wealth) {
    cout << "copy ctor" << endl;
  }
// ...
};