Reusing a float buffer for doubles without undefined behaviour

后端 未结 5 704
情书的邮戳
情书的邮戳 2021-02-05 04:19

In one particular C++ function, I happen to have a pointer to a big buffer of floats that I want to temporarily use to store half the number of doubles. Is there a method to use

5条回答
  •  梦如初夏
    2021-02-05 04:49

    tl;dr Don't alias pointers - at all - unless you tell the compiler that you're going to on the command line.


    The easiest way to do this might be to figure out what compiler switch disables strict aliasing and use it for the source file(s) in question.

    Needs must, eh?


    Thought about this some more. Despite all that stuff about placement new, this is the only safe way.

    Why?

    Well, if you have two pointers of different types pointing to the same address then you have aliased that address and you stand a good chance of fooling the compiler. And it doesn't matter how you assigned values to those pointers. The compiler is not going to remember that.

    So this is the only safe way, and that's why we need std::pun.

提交回复
热议问题