What is sizeof(something) == 0?

不羁岁月 提交于 2019-12-23 09:05:36

问题


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:


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)



回答2:


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++.




回答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++ :)



来源:https://stackoverflow.com/questions/4993650/what-is-sizeofsomething-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!