Aliasing struct and array the C++ way

后端 未结 4 1052
北海茫月
北海茫月 2020-12-05 09:45

This is a C++ followup for another question of mine

In the old days of pre-ISO C, the following code would have surprised nobody:

struct Point {
             


        
4条回答
  •  长情又很酷
    2020-12-05 10:26

    You could use the fact that casting a pointer to intptr_t doing arithmetic and then casting the value back to the pointer type is implemetation defined behavior. I believe it will work on most of the compilers:

    template
    T* increment_pointer(T* a){
      return reinterpret_cast(reinterpret_cast(a)+sizeof(T));
      }
    

    This technic is the most efficient, optimizers seems not to be able to produce optimal if one use table look up: assemblies-comparison

提交回复
热议问题