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

后端 未结 10 2344
粉色の甜心
粉色の甜心 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条回答
  •  伪装坚强ぢ
    2021-02-08 08:28

    sizeof is an C++ operator which yields the number of bytes in the object representation of its operand. Result of sizeof is an implementation-defined constant of type size_t, but should meet the requirements set forth in C++ Standard 5.3.3. You could write your own type traits that will work similar to built-in sizeof operator.

    template struct get_sizeof;
    
    template<> struct get_sizeof          { static const size_t value = 1; };
    template<> struct get_sizeof { static const size_t value = 1; };
    template<> struct get_sizeof           { static const size_t value = 4; };
    template<> struct get_sizeof          { static const size_t value = 4; };
    // etc.
    
    ...
    // sample of use
    static const size_t size = get_sizeof::value;
    char x[get_sizeof::value];
    

    But this have no sense since only creators of the compiler are knows actual values of value for the implementation.

提交回复
热议问题