gpt4 book ai didi

c++ - 指向成员表示的指针

转载 作者:可可西里 更新时间:2023-11-01 15:02:27 26 4
gpt4 key购买 nike

我试图从成员函数中进行一些回调,一切正常,直到我尝试使用从 2 个类派生的模板类作为回调对象时出现以下错误:

error C2440: 'reinterpret_cast' : Pointers to members have different representations; cannot cast between them

这件事告诉我成员函数指针有不同的表示(doh!)

这些表示是什么?它们有什么区别?

最佳答案

Danny Kalev explains this quite nicely :

The Underlying Representation of Pointers to Members

Although pointers to members behave like ordinary pointers, behind the scenes their representation is quite different. In fact, a pointer to member usually consists of a struct containing up to four fields in certain cases. This is because pointers to members have to support not only ordinary member functions, but also virtual member functions, member functions of objects that have multiple base classes, and member functions of virtual base classes. Thus, the simplest member function can be represented as a set of two pointers: one holding the physical memory address of the member function, and a second pointer that holds the this pointer. However, in cases like a virtual member function, multiple inheritance and virtual inheritance, the pointer to member must store additional information. Therefore, you can't cast pointers to members to ordinary pointers nor can you safely cast between pointers to members of different types.

To get a notion of how your compiler represents pointers to members, use the sizeof operator. In the following example, the sizes of a pointer to data member and a pointer to a member function are taken. As you can see, they have different sizes, hence, different representations:

struct A
{
int x;
void f();
};
int A::*pmi = &A::x;
void (A::*pmf)() = &A::f;
int n = sizeof (pmi); // 8 byte with my compiler
int m = sizeof (pmf); // 12 bytes with my compiler

Note that each of these pointers may have a different representation, depending on the class in question and whether the member function is virtual.

关于c++ - 指向成员表示的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13875786/

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