为了使用指针算术,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
指针指向的 ( ) 数据,因为只转换了指针的类型?
为什么它会增加const
?countPointer
是否const
意味着指针指向的数据可能不会被更改?
为什么我必须使用reinterpret_cast<const float*>
而不是在循环内static_cast<const float*>
进行转换?countPointer