How does sizeof work? How can I write my own?

后端 未结 10 2336
粉色の甜心
粉色の甜心 2021-02-08 07:29

I know C++ and know the function sizeof itself but I need to write my own sizeof function so please explain how it works exactly? What does it do with the parameter

10条回答
  •  梦毁少年i
    2021-02-08 08:33

    A non-portable way to write your own sizeof() function is to take advantage of how stack-based variables are often laid out in memory:

    #include 
    using namespace std;
    
    template 
    int mysizeof(T)
    {
      T temp1;
      T temp2;
    
      return (int)&temp1 - (int)&temp2;
    }
    
    int main()
    {
      cout << "sizeof mysizeof" << endl;
    
      char c = 0; short s = 0; int i = 0; long l = 0;
      float f = 0; double d = 0; long double ld = 0;
    
      cout << "char: " << mysizeof(c) << endl;
      cout << "short: " << mysizeof(s) << endl;
      cout << "int: " << mysizeof(i) << endl;
      cout << "long: " << mysizeof(l) << endl;
      cout << "float: " << mysizeof(f) << endl;
      cout << "double: " << mysizeof(d) << endl;
      cout << "long double: " << mysizeof(ld) << endl;
    }
    

    See it in action.
    A 0-parameter version.
    A version that uses one array instead of two variables.

    Warning: This was a fun puzzle, but you should never use this in real code. sizeof is guaranteed to work. This is not. Just because it works on this version of this compiler for this platform does not mean it will work for any other.

    The real operator takes advantage of being a part of the compiler. Sizeof knows how big each type of variable is because it has to know. If the compiler doesn't know how big each type is, it wouldn't be able to lay your program out in memory.

    Edit: Note that all of these flawed examples rely on the original sizeof operator. It's used to space the stack variables, and to create and index array variables.

提交回复
热议问题