gpt4 book ai didi

c++ - C/C++中原始指针和函数指针支持的操作有哪些?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:02 27 4
gpt4 key购买 nike

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

最佳答案

对于函数指针和对象指针,它们都可以编译,但它们的结果只能保证同一完整对象的子对象的地址一致(您可以比较类或数组的两个成员的地址)并且如果您将函数或对象与自身进行比较。

使用 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;
}

虽然所有这些都应该编译(尽管编译器可以自由警告它想要的任何代码片段)。


因为函数类型没有 sizeof值,根据 sizeof 定义的操作pointee 类型的将不起作用,这些包括:

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;

一元 +适用于任何指针类型,并且只会返回它的值,函数指针没有什么特别之处。

+ p; // works. the result is the address stored in p.

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

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

关于c++ - C/C++中原始指针和函数指针支持的操作有哪些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1418068/

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