Reusing a float buffer for doubles without undefined behaviour

后端 未结 5 702
情书的邮戳
情书的邮戳 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:52

    You can achieve this in two ways.

    First:

    void set(float *buffer, size_t index, double value) {
        memcpy(reinterpret_cast(buffer)+sizeof(double)*index, &value, sizeof(double));
    }
    double get(const float *buffer, size_t index) {
        double v;
        memcpy(&v, reinterpret_cast(buffer)+sizeof(double)*index, sizeof(double));
        return v;
    }
    void f(float *buffer) {
        // here, use set and get functions
    }
    

    Second: Instead of float *, you need to allocate a "typeless" char[] buffer, and use placement new to put floats or doubles inside:

    template 
    void setType(char *buffer, size_t size) {
        for (size_t i=0; i(buffer, sizeOfBuffer);
    

    Then use this accessor:

    template 
    T &get(char *buffer, size_t index) {
        return *std::launder(reinterpret_cast(buffer+index*sizeof(T)));
    }
    // use it like this: get(buffer, index) = 33.3f;
    

    A third way could be something like phön's answer (see my comments under that answer), unfortunately I cannot make a proper solution, because of this problem.

提交回复
热议问题