c++ - 关于对象指针的一些困惑

标签 c++ c++17 language-lawyer

问题1:什么是指针值?

A value of a pointer type that is a pointer to or past the end of an object represents the address of the first byte in memory ([intro.memory]) occupied by the object54 or the first byte in memory after the end of the storage occupied by the object, respectively.


这是否意味着指针值是对象的地址?
问题2:如何理解**指针值不变**?
[expr.static.cast]/13

Otherwise, if the original pointer value points to an object a, and there is an object b of type T (ignoring cv-qualification) that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.


考虑以下示例:
#include <iostream>
int main(){
   int a = 0;
   void* tmp = &a;
   char* obj = static_cast<char*>(tmp);
}
根据上面的引用,我们知道tmp的原始指针值指向a,目标指针值指向char类型的对象,因为它们不是指针可互换的,因此句子不变指针值通过转换起作用。这是否意味着obj现在是指向char类型的对象的指针,而该对象的动态类型是int ,如果我误解了pointer value is unchanged,这句话是什么意思?
问题3:如何理解the result is a pointer to b
#include <iostream>
struct Data{
  int c;
}
int main(){
  Data d;
  void* tmp2 = &d;
  int* ptr = static_cast<int*>(tmp2);
}
我们知道tmp2的原始指针值指向d,因此原始指针值指向Data类型的对象,而目标指针指向int类型的对象,并且这两个对象是指针可互换的,因此这句话the result is a pointer to b起作用了。这是否意味着现在指向ptr类型的对象的int指针和该对象的动态类型也是int

最佳答案

A value of a pointer type that is a pointer to or past the end of an object represents the address of the first byte in memory ([intro.memory]) occupied by the object or the first byte in memory after the end of the storage occupied by the object, respectively.


这是否意味着指针值是对象的地址?

没有。
该句子结构“A或B分别表示X或Y”被理解为“条件A表示X,或者条件B表示Y”。
所以这句话的意思是

A value of a pointer type that is a pointer to an object represents the address of the first byte in memory ([intro.memory]) occupied by the object ...



A value of a pointer type that is a pointer past the end of an object represents the address of the first byte in memory after the end of the storage occupied by the object.


分别允许作者在重复这样的扩展时,删除重复的序言。
而且,毕竟,即使是第一种情况,您的意思也不太正确。
这意味着指针(如果是指向对象的指针)表示对象在内存中第一个字节的地址。除非它是指向对象的指针,否则它不会对任何指针的值进行任何说明。
这并不意味着每个指针值都是一个对象的地址,因为指针可以是未初始化的,也可以设置为nullptr,或者设置为原始分配的结果,该原始分配尚未转换为放置new的对象。指针也仍然可以通过该指针保存刚刚delete -d的对象的地址。
我知道该标准不是很容易阅读,特别是如果您不习惯这种风格(或英语)的话-但这意味着您需要付出一些努力才能仔细阅读它。

关于c++ - 关于对象指针的一些困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61227319/

相关文章:

c++ - 为什么那个类型是 double 而不是 float?

c++ - 在两个不同的 OpenCV 窗口中显示相同的鼠标光标

c++ - 用 Go 编写的音频库?

c++ - 链接错误 : Duplicate Symbol

c++ - 为什么 clang 使用 libstdc++ 删除包含 std::optional 的类型上的显式默认构造函数?

c - stdio 错误检测 : ferror versus fclose

c++ - AC_CHECK_LIB在mingw64中失败

c++ - 获取类模板成员的函数类型?

c++ - 通过 std::optional 标准化,我们可以停止在新代码中使用 nullptr 并弃用它吗?

c++ - 使用空指针参数和不可能的后置条件构造标准异常