2012-12-14 3 views
10

내가 멤버 함수에서 일부 콜백을 만들려고을 진술 및 I 콜백 객체로서이 개 클래스에서 파생 된 템플릿 클래스를 사용하려고 할 때까지 나는 다음과 같은 오류 왔을 때 모든 것이 괜찮다고 :포인터는

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를 참조하십시오. –

관련 문제