I've got a tiny little utility class called ObjectCounter
that has no virtual methods and no member-variables; all it contains is a constructor and a destructor, which increment and decrement a global variable, respectively:
int _objectCount = 0; // global
class ObjectCounter
{
public:
ObjectCounter() {printf("DefaultCtor: count=%i\n", ++_objectCount);}
~ObjectCounter() {printf("Dtor: count=%i\n", --_objectCount);}
};
When I want to track the number of instances of another class that my program has created at any given time, I just add an ObjectCounter
as a private-member-variable to that class:
class SomeUserClass
{
public:
SomeUserClass() : _userData(0) {/* empty */}
~SomeUserClass() {/* empty */}
private:
ObjectCounter _objectCounter;
int64_t _userData;
};
(originally I would have that class subclass ObjectCounter
instead, but doing it that way was making my DOxygen class-graphs unnecessarily complex, so I changed to making it into a private member variable)
Today I noticed that adding this "empty" private member variable to my class objects often increases the sizeof the class objects (as reported by sizeof()). For example, the following code shows that sizeof(SomeUserClass)
increases from 8 to 16 on my machine when I include the _objectCounter
member-variable:
int main(int, char **)
{
SomeUserClass sc1;
printf("sizeof(SomeUserClass)=%zu\n", sizeof(SomeUserClass));
printf("sizeof(ObjectCounter)=%zu\n", sizeof(ObjectCounter));
return 0;
}
The increase happens with or without optimizations enabled (via -O3
).
I believe the reason for that is that the compiler is allocating space for the _objectCounter
member-variable simply so that if some other code needs to get a pointer-to-ObjectCounter, a unique address can be supplied. But no code in my program ever actually does reference the _objectCounter
variable; it exists solely to execute its own default-constructor and destructor at the appropriate times.
Given that, is there any way to encourage (or better yet, force) the compiler to not allocate any space for this member-variable?