c – 指向成员表示的指针

前端之家收集整理的这篇文章主要介绍了c – 指向成员表示的指针前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从成员函数做一些回调,一切都ok,直到我尝试使用派生自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.

原文链接:https://www.f2er.com/c/111721.html

猜你在找的C&C++相关文章