加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 指向成员表示的指针

发布时间:2020-12-16 03:20:45 所属栏目:百科 来源:网络整理
导读:我试图从成员函数做一些回调,一切都ok,直到我尝试使用派生自2类的模板类作为回调对象,当我收到以下错误: error C2440: 'reinterpret_cast' : Pointers to members have different representations; cannot cast between them 这个东西告诉我,成员函数指针有
我试图从成员函数做一些回调,一切都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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读