开发者

How can boost::bind call private methods?

boost::bind is extremely handy in a number of situations. One of them is to dispatch/post a method call so that an io_service will make the call later, when it can.

In such situations, boost::bind behaves as one might candidly expect:

#include <boost/asio.hpp>
#include <boost/bind.hpp>

boost::asio::io_service ioService;

class A {
public:     A() {
                // ioService will call B, which is private, how?
                ioService.post(boost::bind(&A::B, thi开发者_JAVA百科s));
            } 
private:    void B() {}
};

void main()
{
    A::A();
    boost::asio::io_service::work work(ioService);
    ioService.run();
}

However, as far as I know boost creates a functor (a class with an operator()()) able to call the given method on the given object. Should that class have access to the private B? I guess not.

What am I missing here ?


You can call any member function via a pointer-to-member-function, regardless of its accessibility. If the function is private, then only members and friends can create a pointer to it, but anything can use the pointer once created.


Its through pointer-to-member-function, boost calls private functions. A member function of the class creates the pointer, and passes it to boost, and later on, boost uses that pointer to call the private function on an object of the class.

Here is one simple illustration of this basic idea:

class A;

typedef void (A::*pf)();

class A 
{
public:     
    pf get_ptr() { return &A::B; } //member function creates the pointer
private:    
    void B() { cout << "called private function" << endl; }
};

int main() {
        A a;
        pf f = a.get_ptr();
        (a.*f)();
        return 0;
}

Output:

called private function

Though it doesn't use boost, but the basic idea is exactly this.

Note that only member functions and friend can create pointer to private member function. Others cannot create it.

Demo at ideone : http://ideone.com/14eUh

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜