我如何才能知道以前在C++中从一个类创建了多少对象
How can I find out how many objects have been created from a class before in C++?
在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> { // ... };
我想这是一个完整的计数器,既有已创建对象的计数器,也有仍然存在的对象的计数器。
这里是原始链接。
相关文章:
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 从多个源构造一个对象,包括一个对象向量
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 检查哪个对象调用了另一个对象的对象方法
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 包装一个对象并假装它是一个 int
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 如何在qt中将信号和插槽与另一个对象连接 --解决了
- 如何使用函数将一个对象的输入复制到另一个对象中
- 选择一个元素而不是一个对象的数组的原因
- 为什么我可以使用 memcpy 将一个对象变量复制到另一个对象变量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 我重载了 << 和 = 运算符。为什么当我将一个对象分配给另一个对象并尝试打印它时,我会被打印出来?
- 打印对象的映射,其中另一个对象作为键
- 如何通过另一个对象中的命令正确地从一个对象返回数据
- 为什么将两个对象分配给另一个对象后,两个对象不一样?
- 绘制一个对象,比较模具缓冲区的两个不同值