Measuring the size of a type without sizeof

Suppose you wanted to check the size (in bytes) of a certain type, WITHOUT using the sizeof() operator. How would you do that?

And what is the size of an empty struct (or class), anyway?

This is a nice occasion to discuss another interesting detail of C++: what would be the size of an empty struct like the following one?

struct x {};

According to the standard, the size of an empty struct (or class) must not be zero (actually, in most implementations it is the size of one byte). This is to ensure that two different objects will always have different addresses. Here’s Stroustrup’s explanation.

We are now after calculating the sizeof of this given struct, without invoking the sizeof operator. Naturally enough, pointer arithmetics can be of great use when attempting such a thing (much like what we had here). A pretty straightforward implementation is hereby provided:

#include <iostream>

struct x {};

template <typename T>
size_t mysizeof () {
	return reinterpret_cast<size_t>(reinterpret_cast<T*>(0) + 1);
}

int main () {
	// prints 1=1:
	std::cout << mysizeof<x>() << "=" << sizeof(x) << std::endl;
}

A thing worth mentioning is that we do not create any living objects in order to carry out our calculation(s). This is an important observation.

A very relevant post on stackoverflow is also available.

One thought on “Measuring the size of a type without sizeof

Leave a Reply