gpt4 book ai didi

c++ - 为什么类中的静态数据成员在将其发送到函数时更新不正确?

转载 作者:搜寻专家 更新时间:2023-10-30 23:55:31 26 4
gpt4 key购买 nike

执行后 Goomba::liveGoombas 等于某个负值。我调试了它但不明白为什么它比构造函数启动更多次析构函数。为什么这里不能正常工作?

// 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();

}

最佳答案

如果您不指定自己的实现,编译器将创建其他构造函数。这些是复制构造函数,对于 C++11 和更新版本,它们是移动构造函数。

当您看到负计数时,可以通过使用编译器生成的构造函数之一来解释。因此,实例数量增加了,但 liveGoombas 没有增加。

要获得准确的计数,您应该将 Goomba 更改为如下所示。

如果您使用启用了移动语义的编译器(C++0x/C++11 和更新版本):

class Goomba
{
public:
static int liveGoombas;

Goomba() { liveGoombas++; }
Goomba(const Goomba&) { liveGoombas++; }
Goomba(Goomba&&) { liveGoombas++; }

// Need to explicitly state we want default or it will be deleted
// due to the above move constructor having been defined.
Goomba & operator = (const Goomba&) = default;

// Not really essential but including for completeness
Goomba & operator = (const Goomba&&) = default;

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

否则:

class Goomba
{
public:
static int liveGoombas;

Goomba() { liveGoombas++; }
Goomba(const Goomba&) { liveGoombas++; }

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

默认赋值运算符很好,因为它们不会创建新实例,而只会修改现有实例。因此,他们不应更改实例计数。

关于c++ - 为什么类中的静态数据成员在将其发送到函数时更新不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31091571/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com