Reusing a float buffer for doubles without undefined behaviour

后端 未结 5 711
情书的邮戳
情书的邮戳 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 05:02

    Here's an alternative approach that's less scary.

    You say,

    ...a float/double union is not possible without...allocating extra space, which defeats the purpose and happens to be costly in my case...

    So just have each union object contain two floats instead of one.

    static_assert(sizeof(double) == sizeof(float)*2, "Assuming exactly two floats fit in a double.");
    union double_or_floats
    {
        double d;
        float f[2];
    };
    
    void f(double_or_floats* buffer)
    {
        // Use buffer of doubles as scratch space.
        buffer[0].d = 1.0;
        // Done with the scratch space.  Start filling the buffer with floats.
        buffer[0].f[0] = 1.0f;
        buffer[0].f[1] = 2.0f;
    }
    

    Of course, this makes indexing more complicated, and calling code will have to be modified. But it has no overhead and it's more obviously correct.

提交回复
热议问题