我正在使用下面的代码来查找某些属性的对齐属性。我知道存储 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/