I can not understand this line - dereference the address of a private member variable or what?

I recently asked about access to the base container of STL adapters . I got a very useful answer:

template <class T, class S, class C> S& Container(priority_queue<T, S, C>& q) { struct HackedQueue : private priority_queue<T, S, C> { static S& Container(priority_queue<T, S, C>& q) { return q.*&HackedQueue::c; } }; return HackedQueue::Container(q); } int main() { priority_queue<SomeClass> pq; vector<SomeClass> &tasks = Container(pq); return 0; } 

Unfortunately, I could not understand this line:

 return q.*&HackedQueue::c; 

What does this line do? In addition, how can this line access a closed container in priority_queue , which is passed to the Container function?

+7
c ++ stl
source share
1 answer

Think of it this way:

 (q).*(&HackedQueue::c); 

First you have HackedQueue :: c, which is simply the name of a member variable. Then you take & HackedQueue :: c, which is a pointer to this member variable. Then you take q , which is just an object reference. Then you use the "bind a pointer to a member by reference" operator .* To bind the member variable indicated by the member pointer using q as this .

Regarding the problem with the private member, priority_queue::c is protected and not private, so it is not surprising that when you exit priority_queue you can access its protected members.

+12
source share

All Articles