-1

为了使用指针算术,void 指针的类型被转换多次。

包含数据的向量来自外部源并返回一个 void 指针以访问其数据。此外,步幅也由外部对象给出,并注意对齐要求。为了使示例简短,它并没有完全反映这两个事实。

// Example data from external source.
struct Data {
    float x;
    float y;

    Data() : x(5), y(8) {}
};

// Example vector from external source.
size_t elements = 3;
std::vector<Data> list;
list.resize(elements);

// Pointer conversions.
const void * voidPointer = list.data(); // The external object containing the vector returns a void pointer.
const uint8_t * countPointer = static_cast<const uint8_t*>(voidPointer);

// Pointer arithmetics.
unsigned stride = sizeof(Data); // The external object returning the stride heeds alignment requirements.
for (size_t counter = 0; counter < elements; ++counter, countPointer += stride) {
    const float * pointsToFloatX = reinterpret_cast<const float*>(countPointer);
    printf("%f, ", *pointsToFloatX); // Expecting something like 5.0000, 5.0000, 5.0000
}

转换为uint8_t不影响float指针指向的 ( ) 数据,因为只转换了指针的类型?

为什么它会增加constcountPointer是否const意味着指针指向的数据可能不会被更改?

为什么我必须使用reinterpret_cast<const float*>而不是在循环内static_cast<const float*>进行转换?countPointer

4

1 回答 1

2

转换为uint8_t不影响float指针指向的 ( ) 数据,因为只转换了指针的类型?

这是正确的。但是在投射指针时,请记住有对齐要求。另外,请注意&list指向vector<Data>; 你会用它list.data()来获取Data*数组。

为什么它会增加constcountPointer是否const意味着指针指向的数据可能不会被更改?

是的。写入float * const以使指针本身为常量或const float * const获取指向常量数据的常量指针。

为什么我必须使用reinterpret_cast<const float*>而不是在循环内static_cast<const float*>进行转换?countPointer

兼容的类型可以被强制转换static_cast,供其他人使用reinterpret_castvoid*与任何其他兼容。reinterpret_cast除非您非常确定自己知道自己在做什么,否则请避免使用。

于 2015-07-26T09:58:45.457 回答