计算不同 类 对象的数量

Counting number of objects of different classes

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

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 中创建一个副本,从而使 class X 的对象总数为 2,而由于 y通过引用传递,class 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 class,并且自动创建的复制构造函数不会增加您的静态变量。

编写一个复制构造函数来执行此操作:

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

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