指针算术的空指针的类型转换
Type conversions of a void pointer for pointer arithmetics
使用指针算法时,会多次转换空指针的类型。
包含数据的向量来自外部源,并返回一个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
?
转换为
uint8_t
不会影响指针指向的(float
(数据,因为只有指针的类型被转换?
没错。但是在投射指针时,请记住有对齐要求。另外,请注意,&list
指向vector<Data>
;您可以使用list.data()
来获得Data*
数组。
为什么
const
在countPointer
上工作,但它会递增?const
是否意味着指针指向的数据可能不会被更改?
是的。写入float * const
以使指针本身恒定,或者写入const float * const
以获得指向恒定数据的恒定指针。
为什么我必须使用
reinterpret_cast<const float*>
而不是static_cast<const float*>
来转换循环内的countPointer
?
兼容类型可以使用static_cast
进行强制转换,其他类型则使用reinterpret_cast
。CCD_ 25与其它任何一个都兼容。除非你非常确定自己在做什么,否则不要使用reinterpret_cast
。
- C++中的双指针类型转换
- 将类指针类型转换为键时出错
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 派生到基本隐式指针类型转换
- 将函数指针类型转换为相应的字符串
- Vulkan API 调试函数指针类型转换错误
- 如何将方法指针类型转换为函数指针类型
- 如何将 void 指针类型转换为 int 指针,然后在其中存储 int
- 将指针类型转换为int会崩溃
- 将一对包含空指针的指针强制转换为一对其他类型的指针
- 将void指针类型转换为int时出现分段错误
- 空指针常量转换为右值
- 查找尾序指针类型转换的代码
- 提取2个指针类型转换为(void*)
- c++中指针类型转换的解释
- C++ 多态性和派生类类型 - "ugly programming"指针类型转换
- c++ /CLI双指针类型转换为ref IntPtr,用于c#访问
- 带和不带引用的指针类型转换
- 将指向结构体或内存对象的空指针强制转换为新结构体
- 将普通指针类型转换为unique_ptr类型是一种不好的做法吗?