I would like to count the number of objects that my program creates over its lifetime. Based on the solution provided here:
how to count the number of objects created in c++
I have the following code:
#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;
}
I expected that since x
is passed by value, a copy of it is made inside fooX
making the total number of objects of class X
to be 2 while since y
is passed by reference, the total number of objects of class Y
to be 1.
Yet, the output of the code is as follows:
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
Why does not the number of X
s created be 2?
A copy constructor is automatically added to your counter
class, and that automatically created copy constructor doesn't increment your static variables.
Write a copy constructor which does that:
counter(counter const&)
{
objects_created++;
objects_alive++;
}
Note that your destructor should probably not be virtual
, unless you intend to delete dynamically created instances of derived classes via pointers or references to counter
. As it stands, it's just premature pessimisation because it needlessly increases the size of your objects.