2021年5月6日星期四

Using reinterpret_cast to pass a value by reference

#include <iostream>    void inc(long& in){   in++;  }    int main(){   int a = 5;   inc(*reinterpret_cast<long*>(&a));     printf("%d\n", a);   return 0;  }  

Above code compiles successfully and prints 6. Is it undefined behaviour? as I'm not really making a reference to anything on the stack. I'm doing an inline cast.

Note that this will not work with a normal cast such as static_cast<long>(a), you will get a compiler error saying:

candidate function not viable: expects an l-value for 1st argument  

Why does *reinterpret_cast<long*>(&a) compile? I'm dereferencing it to a long so the compiler should be able to tell it's not referencing anything.

https://stackoverflow.com/questions/67428388/using-reinterpret-cast-to-pass-a-value-by-reference May 07, 2021 at 10:47AM

没有评论:

发表评论