gpt4 book ai didi

c++ - 指向函数调用的指针与指向成员函数调用的指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:43:54 28 4
gpt4 key购买 nike

我一直想知道为什么调用指向函数的指针与调用指向成员函数的指针在使用取消引用运算符 * 之间存在风格差异,即

void(*fptr)()=&f; // pointer to function f()
fptr(); // call f() via pointer to function

Foo foo; // instance of Foo
void (Foo::*fptr)()=&Foo::f; // pointer to member function f()
(foo.*fptr)(); // call foo.f() via pointer to member function

在第一部分中,您不使用* 运算符通过函数指针调用f(),但必须在调用成员时使用它通过指针 (foo.*fptr)() 函数。为什么会有这种差异?为什么不只使用 (foo.fptr)() 来保持一致性?是否有任何深刻的原因,或者这就是 C++ 的设计方式?

最佳答案

我将引用来自 C++ Common Knowledge 的内容.相关章节的标题是指向成员函数的指针不是指针。作者在那里解释了为什么指向成员函数的指针不能作为指向函数的指针来实现。我将使用这个(它们是不同的东西的事实)作为不同语法的理由:

When you take the address of a non-static member function, you don't get an address; you get a pointer to member function.

(...)

As with a pointer to data member, we need an object or pointer to an object in order to dereference a pointer to member function. (...) In the case of a pointer to member function, we need the object's address to use as (or to calculate) the value of the this pointer for the function call and possibly for other reasons as well.

Note that there is no such thing as a "virtual" pointer to member function. Virtualness is a property of the member function itself, not the pointer that refers to it.

This is one reason why a pointer to member function cannot be implemented, in general, as a simple pointer to function. The implementation of the pointer to member function must store within itself information as to whether the member function to which it refers is virtual or nonvirtual, information about where to find the appropriate virtual function table pointer, an offset to be added to or subtracted from the function's this pointer and possibly other information. A pointer to member function is commonly implemented as a small structure that contains this information, although many other implementations are also in use.

Dereferencing and calling a pointer to member function usually involves examining the stored information and conditionally executing the appropriate virtual or nonvirtual function calling sequence.

恕我直言,考虑到这些差异,可以证明语法差异是合理的,尽管历史设计选择可能发挥了它们的作用。

关于c++ - 指向函数调用的指针与指向成员函数调用的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24344135/

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