2012-12-14 77 views
10

我試圖從成員函數做一些回調和一切正常,直到我試圖用2類爲回調對象派生的模板類時,我得到了以下錯誤:成員指針申述

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

這件事標誌着我說的成員函數指針有不同的表示(DOH!)

這些是什麼表示?他們有什麼區別?

+0

你可能想看看'的std :: bind',它可以綁定一個成員函數和對象,和'的std :: function'可以存儲所產生的回調。 – MSalters

+0

@MSalters我只是做了一些測試,上投一些事情(是不是安全的,我知道 - 但他們的測試)。 – Felics

+0

'std :: function'是要走的路。 – Puppy

回答

16

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.

2

這是微軟的事情:他們使指針成員函數在某些情況下更小,在生產指針即有不同的表示成員函數的成本,就像你剛剛看到的那樣。有一個開關可以關閉它,以便所有指向成員的指針具有相同的表示形式。

+0

了類似的討論,並鏈接到編譯器開關見http://social.msdn.microsoft.com/Forums/en/vclanguage/thread/a9cfa5c4-d90b-4c33-89b1-9366e5fbae74。 –