samedi 27 juin 2015

Why Static data member in class updates not correctly when sending it to a function?

After execution Goomba::liveGoombas is equal to some minus value. I debuged it but did not understand why it launches destructor more times that constructor. Why here it is working not correctly?

// Here is a simple Goomba class. It just keeps track of how many Goombas are alive.

class Goomba
{
public:
  static int liveGoombas;

  Goomba() { liveGoombas++; }
  ~Goomba() { liveGoombas--; }
};

int Goomba::liveGoombas = 0;

// And a Goomba legion class. Please don't change this class.
class GoombaLegion
{
public:
  void add(Goomba goomba)
  {
    goombas.push_back(goomba); //it seems that something wrong in this function
  }

private:
  std::vector<Goomba> goombas;
};

void goombas()
{
  {
    GoombaLegion legion;
  }

  // The legion went out of scope and was destroyed. But how many Goombas are alive?
  std::cout << "There are " << Goomba::liveGoombas << " live goombas" << std::endl;
}



int main()
{
  goombas();

}

Aucun commentaire:

Enregistrer un commentaire