我如何才能知道以前在C++中从一个类创建了多少对象

How can I find out how many objects have been created from a class before in C++?

本文关键字:一个 对象 多少 创建 C++      更新时间:2023-10-16

在C++中之前,我如何知道从一个类创建了多少对象

使用这个基类:

template<class T>
class Counter
{
public:
    Counter()
    {
        ++count;
    }
    Counter(const Counter&)
    {
        ++count;
    }
    static size_t GetCount()
    {
        return count;
    }
private:
    static size_t count;
};
template<class T>
size_t Counter<T>::count = 0;

从中继承并将类类型作为模板参数传递。这是为了获得每个类类型的唯一计数。

class MyClass : public Counter<MyClass>
{
};

现在,您可以计算类的构造次数,而不必修改其自己的构造函数,也不必忘记在其中一个构造函数中增加计数。

不要通过指向Counter的指针进行删除,因为它缺少虚拟析构函数。

您可以添加一个static int instanceCount;成员变量,并在每个类构造函数函数中递增它:

class MyClass {
     static int instanceCount = 0;
public:
      MyClass() {
          ++instanceCount;
      }
      MyClass(const MyClass& rhs) {
          ++instanceCount;
          // Do copy code ...
      }
      static int getCreated() { return instanceCount; }
 };

您只需定义静态整数值,并将其放入类似变量++的构造函数中

class count_opjs{
Public:
 static int counter;
 constructor(){
   counter++;
 }
}
// Initialize static member of class count_opjs
int count_opjs::counter = 0;

我宁愿从wiki页面上复制一个例子,专门介绍一个众所周知的习惯用法CRTP。

它比我午夜能为自己写的东西要完整得多。此外,我发现所有其他回复都遗漏了一些内容,这就是为什么我在列表中又添加了一个回复。

template <typename T> struct counter {
    static int objects_created;
    static int objects_alive;
    counter() {
        ++objects_created;
        ++objects_alive;
    }
    counter(const counter&) {
        ++objects_created;
        ++objects_alive;
    }
protected:
    ~counter() {
        --objects_alive;
    }
};
template <typename T> int counter<T>::objects_created( 0 );
template <typename T> int counter<T>::objects_alive( 0 );
class X : counter<X> { // ... };
class Y : counter<Y> { // ... };

我想这是一个完整的计数器,既有已创建对象的计数器,也有仍然存在的对象的计数器。

这里是原始链接。

相关文章: