Using boost function with boost bind with a map

2019-07-26 22:24发布

问题:

In this code, the line (iter->second)(); calls the function reset(new childClass()). Is this correct ? If this is the case, it is called on which object ?


class BaseClass{
public:
    virtual void foo() { std::cout << "base" << std::endl;}
};

class childClass : public BaseClass {
public:
    virtual void foo() { std::cout << "derived" << std::endl;}
    ~childClass () {
        std::cout << "childClass destructor" << std::endl;   
    }
};

int main()
{
    typedef std::map<std::string, boost::function<void()>> Map_t;

    Map_t g_cmdMap = map_list_of( "cmd",
                boost::bind( static_cast<void( boost::shared_ptr<BaseClass>::* )()>( &boost::shared_ptr<BaseClass>::reset ), 
                  boost::shared_ptr<BaseClass>(new childClass() ) )) ;

    std::map<std::string, boost::function<void()>>::iterator iter;
    iter = g_cmdMap.find( "cmd" );
    (iter->second)();

    return 0;
}

回答1:

the line (iter->second)(); calls the function reset(new childClass()). Is this correct?

No, it invokes reset(). If you want it to be called as reset(new childClass()), you need to pass new childClass() to boost::bind as argument like

boost::bind( static_cast<void( boost::shared_ptr<BaseClass>::* )(BaseClass*)>( 
               &boost::shared_ptr<BaseClass>::reset ), 
             boost::shared_ptr<BaseClass>(new childClass() ),
             new childClass() )

Note that new childClass() itself is evaluated when boost::bind is invoked, not the functor is invoked.

Or you can add a placeholder, and pass new childClass() when call the functor.

it is called on which object ?

It's called on the object copied from the argument passed to boost::bind, i.e. boost::shared_ptr<BaseClass>(new childClass() ).



标签: c++ boost bind