我想计算程序在其生命周期内创建的对象数。基于此处提供的解决方案:
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?
答案 0 :(得分:2)
复制构造函数会自动添加到counter
类中,并且自动创建的复制构造函数不会增加静态变量。
编写一个复制构造函数,它可以:
counter(counter const&)
{
objects_created++;
objects_alive++;
}
请注意,析构函数可能不应该是virtual
,除非您打算通过指针或对counter
的引用删除动态创建的派生类实例。就目前而言,它只是过早的悲观化,因为它会不必要地增加物体的大小。