c++ - `->` 是否意味着取消引用?

标签 c++ pointers alignment

我正在使用下面的代码来查找某些属性的对齐属性。我知道存储 NULL 指针是定义的行为,指针操作也是定义的行为,只有取消引用 NULL(和其他无效值)指针才会调用未定义的行为。我的问题很简单:-> 是否意味着取消引用指针(从而导致下面的代码出现未定义的行为)?

#include <iostream>

void f(void *p)
{
  std::cout << p << std::endl;
}

struct X
{
  int a;
  int b;
};

struct Y
{
  int a[2];
  int b;
};

int main()
{
  X *x = NULL;
  Y *y = NULL;
  f(&x->b);
  f(&y->b);
}

最佳答案

-> 运算符是 *. 运算符的组合。对于

X *x = (struct *)malloc(sizeof(struct));
f(&x->b);

它对x 执行间接寻址以定位它指向的结构,然后选择该结构的b 成员。它类似于调用

 f( &(*x).b ); // which is same as f( & ( (*x).b ) );

因为在你的例子中 x 是一个 NULL 指针,取消引用一个 NULL 指针会调用未定义的行为:
C++11:8.3.2 引用资料(第 4 页):

Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior.

关于c++ - `->` 是否意味着取消引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24396987/

相关文章:

c++ - 如何获得成功的 binary_search 的迭代器?

ruby - 如何获取某个进程正在读取的打开文件的文件指针位置?

c - 使用 C 返回数组

css - 如何使父 div 中的元素垂直居中

c++ - 如何锁定由属于 2 个不同类的 2 个线程修改的数据结构

c++ - 通用运算符 >> 用于 std::vector

c++ - 如何将 Windows GUID 转换为 boost::uuid?

c - 为什么代码会泄漏内存?

html - 如何将图像与 reRestructuredText 居中对齐?

html - 集中一个表时忽略其他表