sizeof
is not a real operator in C++. It is merely special syntax which inserts a constant equal to the size of the argument. sizeof
doesn't need or have any runtime support.
Edit: do you want to know how to determine the size of a class/structure looking at its definition? The rules for this are part of the ABI, and compilers merely implement them. Basically the rules consist of
- size and alignment definitions for primitive types;
- structure, size and alignment of the various pointers;
- rules for packing fields in structures;
- rules about virtual table-related stuff (more esoteric).
However, ABIs are platform- and often vendor-specific, i.e. on x86 and (say) IA64 the size of A
below will be different because IA64 does not permit unaligned data access.
struct A
{
char i ;
int j ;
} ;
assert (sizeof (A) == 5) ; // x86, MSVC #pragma pack(1)
assert (sizeof (A) == 8) ; // x86, MSVC default
assert (sizeof (A) == 16) ; // IA64
sizeof(x)
returns the amount of memory (in bytes) that the variable or type x
occupies. It has nothing to do with the value of the variable.
For example, if you have an array of some arbitrary type T
then the distance between elements of that array is exactly sizeof(T)
.
int a[10];
assert(&(a[0]) + sizeof(int) == &(a[1]));
When used on a variable, it is equivalent to using it on the type of that variable:
T x;
assert(sizeof(T) == sizeof(x));
As a rule-of-thumb, it is best to use the variable name where possible, just in case the type changes:
int x;
std::cout << "x uses " << sizeof(x) << " bytes." << std::endl
// If x is changed to a char, then the statement doesn't need to be changed.
// If we used sizeof(int) instead, we would need to change 2 lines of code
// instead of one.
When used on user-defined types, sizeof
still returns the amount of memory used by instances of that type, but it's worth pointing out that this does not necessary equal the sum of its members.
struct Foo { int a; char b; };
While sizeof(int) + sizeof(char)
is typically 5
, on many machines, sizeof(Foo)
may be 8
because the compiler needs to pad out the structure so that it lies on 4 byte boundaries. This is not always the case, and it's quite possible that on your machine sizeof(Foo)
will be 5, but you can't depend on it.
Best Answer
sizeof
is a compiler built-in operator. It is evaluated at compile-time by the compiler, and there is no runtime code behind it. You cannot write your own.Asking this is akin to asking how you would write your own version of
return
.