gpt4 book ai didi

c++ - reinterpret_casting 一个指针类型的整数和返回是否产生相同的值?

转载 作者:太空狗 更新时间:2023-10-29 23:12:56 26 4
gpt4 key购买 nike

根据 http://en.cppreference.com/w/cpp/language/reinterpret_cast ,众所周知,reinterpret_cast 是一个指向足够大的整数的指针,并且返回相同的值。我想知道反过来是否也符合标准。也就是说,reinterpret_cast 是否是具有足够大小的指针类型的整数并返回相同的值?

最佳答案

不,标准不保证这一点。引用 C++14 (n4140) [expr.reinterpret.cast] 中涉及指针-整数转换的所有部分,强调我的:

4 A pointer can be explicitly converted to any integral type large enough to hold it. The mapping function is implementation-defined. [ Note: It is intended to be unsurprising to those who know the addressing structure of the underlying machine. —end note ] ...

5 A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined. [ Note: Except as described in 3.7.4.3, the result of such a conversion will not be a safely-derived pointer value. —end note ]

因此,从一个整数值开始并将其转换为指针并返回(假设没有大小问题)是实现定义的。这意味着您必须查阅编译器的文档以了解此类往返是否保留值。因此,它肯定不可移植。

关于c++ - reinterpret_casting 一个指针类型的整数和返回是否产生相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42771557/

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