gpt4 book ai didi

C++ double cast void 指针

转载 作者:太空狗 更新时间:2023-10-29 23:48:59 25 4
gpt4 key购买 nike

所以我遇到了这段关于arduino内存的代码

void EEPROM_writeDouble(int address, double value)
{
byte* p = (byte*)(void*)&value;
for (int i = 0; i < sizeof(value); i++)
{
EEPROM.write(address++, *p++);
}
}

让我感兴趣的是这行代码 byte* p = (byte*)(void*)&value; 完成但没有弄清楚或者也许。所以我们有一个 byte(char) 类型的指针,它采用 void* 类型的值的引用并将其转换为字节指针?

最佳答案

double* 转换以来至 byte*不会是有效的 static_castconst_cast , C++ 将请求该转换的 C 风格转换解释为等同于 reinterpret_cast . (我假设 byteunsigned charchar 的类型定义。)

在最初的 C++98 标准和 C++03 标准中,基本上没有保证 reinterpret_cast 是什么会做,只是说结果是“实现定义的”。因此,一次强制转换可能会得到一个指向 double 的存储开头的指针。变量,但从技术上讲,您不能指望这一点。

另一方面,例子中的两次转换,来自double*void*然后从 void*byte* , 有效 static_cast转换,因此 C 风格的转换都具有 static_cast 的行为.还有一个 static_cast至或来自(非空)[cv] void*一直保证void*指向对象存储的开头,导致指向虚构的 byte 的指针重叠 double 的存储目的。 (并且从真正属于不同类型对象的存储中的 unsigned charchar 读取是严格别名规则的特定异常(exception),所以没关系。)

请注意,从 C++11 标准开始,reinterpret_cast 的行为,因此 C 风格的转换,更具体地用于某些类别的指针转换:([expr.reinterpret.cast]/7)

An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of type "pointer to T1" is converted to the type "pointer to cv T2", the result is static_cast<cvT2*>(static_cast<cvvoid*>(v)) if both T1 and T2 are standard-layout types and the alignment requirements of T2 are no stricter than those of T1, or if either type is void. Converting a prvalue of type "pointer to T1" to the type "pointer to T2" (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value. The result of any other such pointer conversion is unspecified.

因此使用最近的标准模式,不再需要这两个类型转换。 (代码可能是较早编写的,或者可能仍需要在多个 C++ 版本下工作,或者可能只是使用旧习惯编写的。尽管使用 C++ 风格的转换来说明您真正想要的转换逻辑类型几乎总是比使用 C 风格的转换更好的主意。)

关于C++ double cast void 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48738197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com