gpt4 book ai didi

c++ - uintptr_t 存储的是指针的地址还是它的值?

转载 作者:行者123 更新时间:2023-11-30 01:03:54 25 4
gpt4 key购买 nike

假设我有以下代码:

Foo *foo = something();
uintptr_t bar = reinterpret_cast<uintptr_t>(foo);

bar代表的是foo的地址还是foo指向的地址?我相信这是 foo 的地址,但我想确定我没有弄错。

一些说明

What is uintptr_t data type解释说

In C99, it is defined as "an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer".

但这并没有说明正在存储什么。编译器是否可以将 foo 指向的地址存储在 bar 中,然后在转换回 Foo 时构造一个具有不同地址的新指针来自uintptr_t?也许我误解了指针比较,但是由于它们指向同一个对象,所以它们比较不会相等吗?

我想我正在寻找一些关于是否添加以下行的迂腐的清晰度:

Foo *foo2 = reinterpret_cast<Foo *>(bar);

这里到底发生了什么?未定义的行为? foo2 只是指向与 foo 相同的对象?

最佳答案

这取决于 Actor 阵容的应用范围。

uintptr_t bar = (uintptr_t)foo;中,它将foo的值(指向对象的地址)存储在bar中。

更喜欢使用 C++ 强制转换,它们向读者传达更多信息,并且在维护过程中更加健壮 - 最佳实践:

uintptr_t bar = reinterpret_cast<uintptr_t>(foo);

关于c++ - uintptr_t 存储的是指针的地址还是它的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51537358/

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