6

I have a template that takes a struct with different values, for example:

struct Something
{
    char str[10];
    int value;
    ...
    ...
};

And inside the function I use the sizeof operator: jump in memory sizeof(Something);

Sometimes I would like to not jump anything at all; I want sizeof to return zero. If I put in an empty struct it will return 1; what can I put in the template to make sizeof return zero?

1

3 Answers 3

21

sizeof will never be zero. (Reason: sizeof (T) is the distance between elements in an array of type T[], and the elements are required to have unique addresses).

Maybe you can use templates to make a sizeof replacement, that normally uses sizeof but is specialized for one particular type to give zero.

e.g.

template <typename T>
struct jumpoffset_helper
{
    enum { value = sizeof (T) };
};


template <>
struct jumpoffset_helper<Empty>
{
    enum { value = 0 };
};

#define jumpoffset(T) (jumpoffset_helper<T>::value)
4
  • 2
    You can't overload the sizeof operator Feb 14, 2011 at 15:05
  • 5
    @Let_Me_Be - I don't think that is what was suggested, but you can make something that looks and behaves similarly, but returns 0 for the cases you care about.
    – Flexo
    Feb 14, 2011 at 15:05
  • @awoodland Well, yes, but it can't be called sizeof. Feb 14, 2011 at 20:52
  • 4
    @Let_Me_Be: I never said I was going to redefine the sizeof keyword, but make something new that could be used instead.
    – Ben Voigt
    Feb 14, 2011 at 21:18
14

What do you think about it?

 #include <iostream>
 struct ZeroMemory {
     int *a[0];
 };
 int main() {
     std::cout << sizeof(ZeroMemory);
 }

Yes, output is 0.

But this code is not standard C++.

1
3

No object in C++ may have a 0 size according to the C++ standard. Only base-class subobjects MAY have 0 size but then you can never call sizeof on those. What you want to achieve is inachievable :) or, to put it mathematically, the equation

sizeof x == 0 has no object solution in C++ :)

4
  • The sizeof an empty struct in C would be 0 though, correct? What's the rationale behind enforcing it to be 1 in the C++ standard? And what's the "1", a mandatory padding byte of unknown value?
    – Lundin
    Feb 14, 2011 at 15:19
  • because arrays of an empty struct still have to be addressable
    – jk.
    Feb 14, 2011 at 15:41
  • @lundin: It's not actually necessarily 1 byte. It can be 4 (and on my machine it is) or any other nonegative integer for that matter Feb 14, 2011 at 15:43
  • 1
    @Lundin: Indeed. I have just experimented with C and C++ (gcc 4.3.2) and the sizeof operator on an empty struct is 0 in C and 1 in C++.
    – JeremyP
    Feb 14, 2011 at 15:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.