Measuring the size of a type without sizeof

Posted on: 25/11/2009

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.


1 Response to "Measuring the size of a type without sizeof"

Very clever. Took me a little bit to see the magic of the + 1.

… Alan

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: