gpt4 book ai didi

c++ - 计算不同类别的对象数量

转载 作者:行者123 更新时间:2023-11-30 03:25:46 24 4
gpt4 key购买 nike

我想计算我的程序在其生命周期内创建的对象数量。基于此处提供的解决方案:

how to count the number of objects created in c++

我有以下代码:

#include <iostream>
using namespace::std;
using std::cout;
using std::endl;

template <typename T>
struct counter
{
counter()
{
objects_created++;
objects_alive++;
}

virtual ~counter()
{
--objects_alive;
}
static int objects_created;
static int objects_alive;
};
template <typename T> int counter<T>::objects_created(0);
template <typename T> int counter<T>::objects_alive(0);

class X : counter<X>
{
int a;
};

class Y : counter<Y>
{
int b;
};

void fooX(class X x) {
cout << "passing object" << endl;
}

void fooY(class Y& y) {
cout << "passing reference" << endl;
}

int main()
{
cout << "created: " << " X:" << counter<X>::objects_created << " Y:" << counter<Y>::objects_created << endl;
cout << "alive: " << " X:" << counter<X>::objects_alive << " Y:" << counter<Y>::objects_alive << endl;
X x;
Y y;
cout << "created: " << " X:" << counter<X>::objects_created << " Y:" << counter<Y>::objects_created << endl;
cout << "alive: " << " X:" << counter<X>::objects_alive << " Y:" << counter<Y>::objects_alive << endl;
fooX(x);
fooY(y);
cout << "created: " << " X:" << counter<X>::objects_created << " Y:" << counter<Y>::objects_created << endl;
cout << "alive: " << " X:" << counter<X>::objects_alive << " Y:" << counter<Y>::objects_alive << endl;
int ui;
cin >> ui;
}

我预计由于 x 是按值传递的,所以它的拷贝会在 fooX 中制作,从而使 X 类的对象总数 为 2 而由于 y 是通过引用传递的,因此 Y 类 的对象总数为 1。

然而,代码的输出如下:

created:  X:0 Y:0
alive: X:0 Y:0
created: X:1 Y:1
alive: X:1 Y:1
passing object
passing reference
created: X:1 Y:1
alive: X:0 Y:1

为什么创建的X数量不是2?

最佳答案

复制构造函数会自动添加到您的 counter 类中,并且自动创建的复制构造函数不会增加您的静态变量。

写一个复制构造函数来完成:

counter(counter const&)
{
objects_created++;
objects_alive++;
}

请注意,您的析构函数可能不应该是虚拟的,除非您打算通过指针或对counter 的引用删除动态创建的派生类实例。就目前而言,这只是过早的悲观情绪,因为它不必要地增加了对象的大小。

关于c++ - 计算不同类别的对象数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48813611/

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