C/C++中原始指针和函数指针支持的操作是什么?

yes*_*aaj 6 c c++ pointers function-pointers

函数指针支持的所有操作与原始指针有什么不同?是>,<,<=,> =原始指针支持的运算符如果有,有什么用?

Joh*_*itb 14

对于函数和对象指针,它们都会编译但是它们的结果只保证对于同一个完整对象的子对象的地址是一致的(你可以比较一个类或数组的两个成员的地址),如果你比较一个函数或反对自己.

使用std::less<>,std::greater<>等将与任何指针类型的工作,并提供一致的结果,即使各个内置的操作的结果是不确定的:

void f() { }
void g() { }

int main() {
  int a, b;

  ///// not guaranteed to pass
  assert((&a < &b) == (&a < &b));

  ///// guaranteed to pass
  std::less<int*> lss1;
  assert(lss1(&a, &b) == lss1(&a, &b));
  // note: we don't know whether lss1(&a, &b) is true or false. 
  //       But it's either always true or always false. 

  ////// guaranteed to pass
  int c[2];
  assert((&c[0] < &c[1]) == (&c[0] < &c[1]));
  // in addition, the smaller index compares less:
  assert(&c[0] < &c[1]);

  ///// not guaranteed to pass
  assert((&f < &g) == (&f < &g));

  ///// guaranteed to pass
  assert((&g < &g) == (&g < &g));
  // in addition, a function compares not less against itself. 
  assert(!(&g < &g));

  ///// guaranteed to pass
  std::less<void(*)()> lss2;
  assert(lss2(&f, &g) == lss2(&f, &g));
  // note: same, we don't know whether lss2(&f, &g) is true or false.

  ///// guaranteed to pass
  struct test {
    int a;
  // no "access:" thing may be between these!
    int b;

    int c[1];
  // likewise here
    int d[1];

    test() {
      assert((&a < &b) == (&a < &b));
      assert((&c[0] < &d[0]) == (&c[0] < &d[0]));

      // in addition, the previous member compares less:
      assert((&a < &b) && (&c[0] < &d[0]));
    }
  } t;
}
Run Code Online (Sandbox Code Playgroud)

这一切都应该编译(虽然编译器可以自由地警告它想要的任何代码片段).


由于函数类型没有sizeof值,因此根据sizeof指针类型定义的操作将不起作用,这些操作包括:

void(*p)() = ...;
// all won't work, since `sizeof (void())` won't work.
// GCC has an extension that treats it as 1 byte, though.
p++; p--; p + n; p - n; 
Run Code Online (Sandbox Code Playgroud)

一元+可以处理任何指针类型,并且只返回它的值,对于函数指针没有什么特别之处.

+ p; // works. the result is the address stored in p.
Run Code Online (Sandbox Code Playgroud)

最后请注意,指向函数指针的指针不再是函数指针:

void (**pp)() = &p;
// all do work, because `sizeof (void(*)())` is defined.
pp++; pp--; pp + n; pp - n;
Run Code Online (Sandbox Code Playgroud)