如何计算在c ++中创建的对象数 [英] how to count the number of objects created in c++
本文介绍了如何计算在c ++中创建的对象数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何计算在c ++中创建的对象数量
how to count the number of objects created in c++
使用一个简单的例子解释
pls explain with a simple example
推荐答案
使用静态计数器创建模板类。
Create template class with a static counter.
然后,应用程序中的每个对象都将扩展此模板类。
Each object in your application would then extend this template class.
当构造函数被调用时,增量静态计数(静态变量是每个类的 - 由该类的所有对象共享)。
When constructor is called increment static count (static variable is per class - shared by all objects of that class).
对象计数器使用奇怪的重复模板模式:
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>
{
// ...
};
class Y : counter<Y>
{
// ...
};
完整使用:
int main()
{
X x1;
{
X x2;
X x3;
X x4;
X x5;
Y y1;
Y y2;
} // objects gone
Y y3;
cout << "created: "
<< " X:" << counter<X>::object_created
<< " Y:" << counter<Y>::object_created
<< endl;
cout << "alive: "
<< " X:" << counter<X>::object_alive
<< " Y:" << counter<Y>::object_alive
<< endl;
}
输出:
created: X:5 Y:3
alive: X:1 Y:1
这篇关于如何计算在c ++中创建的对象数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文