如何重新解释强制转换数组,这样做安全吗?

问题描述 投票:1回答:3
// this boxes8a contains a flat array of floats
// There are n boxes and the array is n * 8 long
float* boxes8a = ...;

我想将其重新解释为Box数组,其中每个Box包含4个点的数组。每个点包含2个浮点数,(x,y)

struct Box
{
  point points[4]
}

struct point
{
   float x, y
}

Q1:如何将float* boxes8a转换为Box数组?

Q2:这样做是一种好习惯吗?

c++
3个回答
2
投票

我如何将float* boxes8a转换为Box的数组?] >>

危险地。

//Undefined Behavior, might not do what you want it to do!
Box* boxes = reinterpret_cast<Box*>(boxes8a); 

这样做是一种好的做法吗?

编号

这在C ++中被认为是未定义的行为,尽管许多编译器会为您提供看起来像在您尝试这样做的结果,但我不能建议这样做。最好的解决方案是将值简单复制到Box对象中,然后让这些对象拥有自己的数据。

std::vector<Box> boxes(n);
for(size_t i = 0; i < n; i++) {
    for(int j = 0; j < 4; j++)
        boxes[i][j] = point{boxes8a[i*8 + j*2 + 0], boxes8a[i*8 + j*2 + 1]};
}

或者,冒着听起来像是面向数据的设计Cultists

支持者之一的风险,您可能会考虑让Box对象仅包含一个指向数组中数据开始位置的指针:
class point {
    float* data;
public:
    point(float* data) : data(data) {}

    float& x() const {return *data;}
    float& y() const {return *(data+1);}
};

class Box {
    float* data;
public:
    Box(float* data) : data(data) {}

    point operator[](size_t index) const {
        return point(data + index * 2);
    }
};

int main() {
    std::vector<Box> boxes;
    for(size_t i = 0; i < n; i++)
        boxes.emplace_back(boxes8a + i*8);

    boxes[3][3].x() = 34.7; //Will alter the original value in boxes8a!
}

此方法将允许Box对象对原始float*数组进行别名而不破坏别名规则。


3
投票

Q1:如何将float* boxes8a转换为Box数组?


0
投票

Q1:如何将float * box8a转换为Box数组?

© www.soinside.com 2019 - 2024. All rights reserved.